diff --git a/docs/source/python-api-reference/mooncake-store.md b/docs/source/python-api-reference/mooncake-store.md index bb3610b17b..64f41ac562 100644 --- a/docs/source/python-api-reference/mooncake-store.md +++ b/docs/source/python-api-reference/mooncake-store.md @@ -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_` 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_`: the shard payload + - `key_tp__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_` and `key_tp__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() @@ -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_` and `key_tp__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 diff --git a/mooncake-integration/integration_utils.h b/mooncake-integration/integration_utils.h index 8179b72c35..3c2e7cf0cd 100644 --- a/mooncake-integration/integration_utils.h +++ b/mooncake-integration/integration_utils.h @@ -6,6 +6,7 @@ #include #include +#include namespace py = pybind11; @@ -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) { + switch (static_cast(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 diff --git a/mooncake-integration/store/store_py.cpp b/mooncake-integration/store/store_py.cpp index b8650e5d92..5a27c5de6f 100644 --- a/mooncake-integration/store/store_py.cpp +++ b/mooncake-integration/store/store_py.cpp @@ -62,6 +62,19 @@ struct PyTensorInfo { } }; +bool validate_serialized_tensor_buffer(uintptr_t buffer_ptr, size_t size, + const std::string &buffer_name) { + if (buffer_ptr == 0) { + LOG(ERROR) << buffer_name << " pointer cannot be null"; + return false; + } + if (size <= sizeof(TensorMetadata)) { + LOG(ERROR) << buffer_name << " size too small for tensor metadata"; + return false; + } + return true; +} + PyTensorInfo extract_tensor_info(const py::object &tensor, const std::string &key_name = "") { PyTensorInfo info = { @@ -225,6 +238,21 @@ pybind11::object buffer_to_tensor(BufferHandle *buffer_handle, char *usr_buffer, } } +py::object decode_serialized_tensor_buffer(uintptr_t buffer_ptr, size_t size, + const std::string &context) { + if (!validate_serialized_tensor_buffer(buffer_ptr, size, context)) { + return py::none(); + } + + py::object tensor = + buffer_to_tensor(nullptr, reinterpret_cast(buffer_ptr), + static_cast(size)); + if (tensor.is_none()) { + LOG(ERROR) << "Failed to decode tensor buffer for " << context; + } + return tensor; +} + std::vector> CastAddrs2Ptrs( const std::vector> &all_buffer_ptrs) { std::vector> all_buffers; @@ -240,6 +268,15 @@ std::vector> CastAddrs2Ptrs( return all_buffers; } +std::vector CastAddrs2Ptrs(const std::vector &buffer_ptrs) { + std::vector buffers; + buffers.reserve(buffer_ptrs.size()); + for (uintptr_t ptr : buffer_ptrs) { + buffers.push_back(reinterpret_cast(ptr)); + } + return buffers; +} + // Helper function to convert ErrorCode to Python return value // ErrorCode values are already negative, so just cast to int inline int to_py_ret(ErrorCode error_code) { @@ -276,7 +313,7 @@ class MooncakeStorePyWrapper { return store_->health_check(); } - std::string get_tp_key_name(const std::string &base_key, int rank) { + static std::string get_tp_key_name(const std::string &base_key, int rank) { return base_key + "_tp_" + std::to_string(rank); } @@ -351,6 +388,205 @@ class MooncakeStorePyWrapper { return batch_get_tensor(shard_keys); } + static std::string get_chunk_meta_key_name(const std::string &base_key, + int rank) { + return get_tp_key_name(base_key, rank) + "_meta"; + } + + static std::string get_global_meta_key_name(const std::string &base_key) { + return base_key + "_global_meta"; + } + + static std::pair calculate_chunk_range(int64_t dim_size, + int tp_rank, + int tp_size) { + int64_t base = dim_size / tp_size; + int extra = dim_size % tp_size; + int64_t start_idx = base * tp_rank + std::min(tp_rank, extra); + int64_t size = base + (tp_rank < extra ? 1 : 0); + return {start_idx, size}; + } + + static void batch_put_metadata_and_update_results( + PyClient *store, const std::vector &meta_keys, + const std::vector &meta_buffers, + const std::vector &meta_sizes, + const std::vector &meta_indices, std::vector &results, + const ReplicateConfig &config) { + if (meta_keys.empty()) return; + + std::vector> meta_spans; + meta_spans.reserve(meta_keys.size()); + for (size_t i = 0; i < meta_keys.size(); ++i) { + meta_spans.emplace_back( + reinterpret_cast(meta_buffers[i]), meta_sizes[i]); + } + + int meta_ret; + { + py::gil_scoped_release release_gil; + meta_ret = store->put_batch(meta_keys, meta_spans, config); + } + if (meta_ret != 0) { + for (size_t j = 0; j < meta_indices.size(); ++j) { + results[meta_indices[j]] = meta_ret; + } + } + } + + static void validate_split_dim(const TensorMetadata &tensor_meta, + int split_dim) { + if (tensor_meta.ndim <= 0 || tensor_meta.ndim > 4) { + throw std::runtime_error("Invalid tensor ndim: " + + std::to_string(tensor_meta.ndim)); + } + if (split_dim < 0 || split_dim >= tensor_meta.ndim) { + throw std::runtime_error("Invalid split_dim: " + + std::to_string(split_dim)); + } + } + + static void calculate_full_shape( + const TensorMetadata &chunk_meta, int split_dim, int tp_size, + const std::optional> &full_shape_arg, + int64_t full_shape[4]) { + validate_split_dim(chunk_meta, split_dim); + + if (full_shape_arg.has_value()) { + const auto &arg_shape = full_shape_arg.value(); + if (arg_shape.size() != static_cast(chunk_meta.ndim)) { + throw std::runtime_error("Provided full_shape dim mismatch"); + } + for (int i = 0; i < 4; ++i) { + full_shape[i] = (i < chunk_meta.ndim) ? arg_shape[i] : -1; + } + } else { + for (int i = 0; i < chunk_meta.ndim; i++) { + if (i == split_dim) { + full_shape[i] = chunk_meta.shape[i] * tp_size; + } else { + full_shape[i] = chunk_meta.shape[i]; + } + } + for (int i = chunk_meta.ndim; i < 4; ++i) { + full_shape[i] = -1; + } + } + } + + static GlobalMetadata create_global_metadata( + const TensorMetadata &tensor_meta, int split_dim, int put_tp_size, + const int64_t *full_shape) { + validate_split_dim(tensor_meta, split_dim); + + GlobalMetadata global_meta; + global_meta.dtype = tensor_meta.dtype; + global_meta.ndim = tensor_meta.ndim; + global_meta.split_dim = split_dim; + global_meta.put_tp_size = put_tp_size; + for (int i = 0; i < 4; i++) { + global_meta.shape[i] = full_shape[i]; + } + return global_meta; + } + + static void validate_chunk_matches_tp_plan(const TensorMetadata &chunk_meta, + const int64_t *full_shape, + int split_dim, int tp_rank, + int tp_size) { + validate_split_dim(chunk_meta, split_dim); + int64_t dim_size = full_shape[split_dim]; + auto [expected_start_idx, expected_size] = + calculate_chunk_range(dim_size, tp_rank, tp_size); + (void)expected_start_idx; + if (chunk_meta.shape[split_dim] != expected_size) { + throw std::runtime_error( + "Chunk shape does not match the default TP sharding plan for " + "the provided full_shape"); + } + } + + static void cleanup_partial_tp_chunk_puts( + PyClient *store, const std::vector &base_keys, + const std::vector &results, int tp_rank, bool remove_global_meta) { + for (size_t i = 0; i < base_keys.size(); ++i) { + if (results[i] == 0) continue; + store->remove(get_tp_key_name(base_keys[i], tp_rank)); + store->remove(get_chunk_meta_key_name(base_keys[i], tp_rank)); + if (remove_global_meta) { + store->remove(get_global_meta_key_name(base_keys[i])); + } + } + } + + static void cleanup_partial_tp_puts(PyClient *store, + const std::vector &keys, + const std::vector &results, + int tp_size) { + for (size_t i = 0; i < keys.size(); ++i) { + if (results[i] == 0) continue; + for (int rank = 0; rank < tp_size; ++rank) { + store->remove(get_tp_key_name(keys[i], rank)); + store->remove(get_chunk_meta_key_name(keys[i], rank)); + } + store->remove(get_global_meta_key_name(keys[i])); + } + } + + int store_tensor_tp_metadata( + const std::string &logical_key, int put_tp_rank, int put_tp_size, + int split_dim, const TensorMetadata &tensor_meta, + const int64_t *full_shape, + const ReplicateConfig &config = ReplicateConfig{}) { + int64_t dim_size = full_shape[split_dim]; + auto [start_idx, calculated_size] = + calculate_chunk_range(dim_size, put_tp_rank, put_tp_size); + (void)calculated_size; + int64_t chunk_size = tensor_meta.shape[split_dim]; + + ChunkMetadata chunk_meta{start_idx, chunk_size}; + + std::string chunk_meta_key = + get_chunk_meta_key_name(logical_key, put_tp_rank); + int ret; + { + py::gil_scoped_release release_gil; + ret = store_->put(chunk_meta_key, + std::span( + reinterpret_cast(&chunk_meta), + sizeof(ChunkMetadata)), + config); + } + if (ret != 0) { + LOG(ERROR) << "Failed to store chunk metadata for rank " + << put_tp_rank; + return ret; + } + + if (put_tp_rank == 0) { + GlobalMetadata global_meta = create_global_metadata( + tensor_meta, split_dim, put_tp_size, full_shape); + std::string global_meta_key = get_global_meta_key_name(logical_key); + + { + py::gil_scoped_release release_gil; + ret = store_->put( + global_meta_key, + std::span( + reinterpret_cast(&global_meta), + sizeof(GlobalMetadata)), + config); + } + + if (ret != 0) { + LOG(ERROR) << "Failed to store global metadata, ret=" << ret; + return ret; + } + } + + return 0; + } + pybind11::object get_tensor(const std::string &key) { if (!is_client_initialized()) { LOG(ERROR) << "Client not initialized"; @@ -563,6 +799,65 @@ class MooncakeStorePyWrapper { ReplicateConfig{}); // Default config } + int put_tensor_chunk_with_tp( + const std::string &logical_key, pybind11::object tensor_chunk, + int put_tp_rank, int put_tp_size = 1, int split_dim = 0, + const std::optional> &full_shape_arg = + std::nullopt, + const ReplicateConfig &config = ReplicateConfig{}) { + if (!is_client_initialized() || use_dummy_client_) { + LOG(ERROR) << "Client not initialized or Dummy client not " + "supported for tensors"; + return to_py_ret(ErrorCode::INVALID_PARAMS); + } + + if (!tensor_chunk.attr("is_contiguous")().cast()) { + tensor_chunk = tensor_chunk.attr("contiguous")(); + } + + if (put_tp_size <= 1) { + return put_tensor(logical_key, tensor_chunk); + } + if (put_tp_rank < 0 || put_tp_rank >= put_tp_size) { + LOG(ERROR) << "Invalid put_tp_rank: " << put_tp_rank + << ", must be in range [0, " << put_tp_size << ")"; + return to_py_ret(ErrorCode::INVALID_PARAMS); + } + + auto info = extract_tensor_info(tensor_chunk, logical_key); + if (!info.valid()) { + return to_py_ret(ErrorCode::INVALID_PARAMS); + } + + int64_t full_shape[4] = {0}; + try { + calculate_full_shape(info.metadata, split_dim, put_tp_size, + full_shape_arg, full_shape); + validate_chunk_matches_tp_plan(info.metadata, full_shape, split_dim, + put_tp_rank, put_tp_size); + } catch (const std::exception &e) { + LOG(ERROR) << e.what(); + return to_py_ret(ErrorCode::INVALID_PARAMS); + } + + std::string chunk_key = get_tp_key_name(logical_key, put_tp_rank); + int ret = put_tensor_impl(chunk_key, tensor_chunk, config); + if (ret != 0) { + return ret; + } + + ret = store_tensor_tp_metadata(logical_key, put_tp_rank, put_tp_size, + split_dim, info.metadata, full_shape, + config); + if (ret != 0) { + cleanup_partial_tp_chunk_puts(store_.get(), {logical_key}, {ret}, + put_tp_rank, put_tp_rank == 0); + return ret; + } + + return 0; + } + int put_tensor_with_tp_impl( const std::string &key, pybind11::object tensor, const ReplicateConfig &config = ReplicateConfig{}, int tp_rank = 0, @@ -578,9 +873,8 @@ class MooncakeStorePyWrapper { for (int rank = 0; rank < tp_size; ++rank) { pybind11::object chunk = chunks[rank].attr("contiguous")(); - std::string tp_key = get_tp_key_name(key, rank); - - int ret = put_tensor_impl(tp_key, chunk, config); + int ret = put_tensor_chunk_with_tp( + key, chunk, rank, tp_size, split_dim, std::nullopt, config); if (ret != 0) return ret; } return 0; @@ -703,18 +997,24 @@ class MooncakeStorePyWrapper { std::vector processed_indices; std::vector final_results(base_keys.size(), to_py_ret(ErrorCode::INVALID_PARAMS)); + std::vector tensor_infos(base_keys.size()); + std::vector> chunk_split_sizes(base_keys.size()); try { - // Chunking phase (GIL Held) for (size_t i = 0; i < base_keys.size(); ++i) { py::object tensor = tensors_list[i]; - // Quick validation if (tensor.is_none() || !tensor.attr("shape").cast()) { final_results[i] = to_py_ret(ErrorCode::INVALID_PARAMS); continue; } + 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; + } + py::tuple chunks = tensor.attr("chunk")(tp_size, split_dim).cast(); if (static_cast(chunks.size()) != tp_size) { @@ -723,37 +1023,102 @@ class MooncakeStorePyWrapper { } processed_indices.push_back(i); + chunk_split_sizes[i].resize(tp_size); for (int rank = 0; rank < tp_size; ++rank) { + py::object chunk = chunks[rank].attr("contiguous")(); all_chunk_keys.push_back( get_tp_key_name(base_keys[i], rank)); - all_chunks_list.append(chunks[rank].attr( - "contiguous")()); // Ensure contiguous here + all_chunks_list.append(chunk); + py::tuple chunk_shape = + chunk.attr("shape").cast(); + chunk_split_sizes[i][rank] = + chunk_shape[split_dim].cast(); } } if (all_chunk_keys.empty()) return final_results; - // Reuse the standard batch_put implementation std::vector chunk_results = batch_put_tensor_impl(all_chunk_keys, all_chunks_list, config); - // Aggregate results for (size_t i = 0; i < processed_indices.size(); ++i) { size_t original_idx = processed_indices[i]; - bool all_ok = true; + final_results[original_idx] = 0; for (int j = 0; j < tp_size; ++j) { int res = chunk_results[i * tp_size + j]; if (res != 0) { - final_results[original_idx] = res; // First error wins - all_ok = false; + final_results[original_idx] = res; break; } } - if (all_ok) { - final_results[original_idx] = 0; + } + + cleanup_partial_tp_puts(store_.get(), base_keys, final_results, + tp_size); + + size_t valid_count = 0; + for (size_t idx : processed_indices) { + if (final_results[idx] == 0) valid_count++; + } + + std::vector chunk_meta_storage; + std::vector chunk_meta_keys; + std::vector chunk_meta_buffers; + std::vector chunk_meta_sizes; + std::vector chunk_meta_indices; + chunk_meta_storage.reserve(valid_count * tp_size); + + for (size_t idx : processed_indices) { + if (final_results[idx] != 0) continue; + + int64_t dim_size = tensor_infos[idx].metadata.shape[split_dim]; + for (int rank = 0; rank < tp_size; ++rank) { + auto [start_idx, calculated_size] = + calculate_chunk_range(dim_size, rank, tp_size); + (void)calculated_size; + int64_t chunk_size = chunk_split_sizes[idx][rank]; + + chunk_meta_storage.push_back( + ChunkMetadata{start_idx, chunk_size}); + chunk_meta_keys.push_back( + get_chunk_meta_key_name(base_keys[idx], rank)); + chunk_meta_buffers.push_back(&chunk_meta_storage.back()); + chunk_meta_sizes.push_back(sizeof(ChunkMetadata)); + chunk_meta_indices.push_back(idx); } } + batch_put_metadata_and_update_results( + store_.get(), chunk_meta_keys, chunk_meta_buffers, + chunk_meta_sizes, chunk_meta_indices, final_results, config); + + std::vector global_meta_storage; + std::vector global_meta_keys; + std::vector global_meta_buffers; + std::vector global_meta_sizes; + std::vector global_meta_indices; + global_meta_storage.reserve(valid_count); + + for (size_t idx : processed_indices) { + if (final_results[idx] != 0) continue; + + validate_chunk_matches_tp_plan(tensor_infos[idx].metadata, + tensor_infos[idx].metadata.shape, + split_dim, 0, tp_size); + global_meta_storage.push_back(create_global_metadata( + tensor_infos[idx].metadata, split_dim, tp_size, + tensor_infos[idx].metadata.shape)); + global_meta_keys.push_back( + get_global_meta_key_name(base_keys[idx])); + global_meta_buffers.push_back(&global_meta_storage.back()); + global_meta_sizes.push_back(sizeof(GlobalMetadata)); + global_meta_indices.push_back(idx); + } + + batch_put_metadata_and_update_results( + store_.get(), global_meta_keys, global_meta_buffers, + global_meta_sizes, global_meta_indices, final_results, config); + } catch (const std::exception &e) { LOG(ERROR) << "Batch put with TP failed: " << e.what(); } @@ -761,6 +1126,178 @@ class MooncakeStorePyWrapper { return final_results; } + std::vector batch_put_tensor_chunk_with_tp( + const std::vector &base_keys, + const pybind11::list &tensor_chunks, int tp_rank = 0, int tp_size = 1, + int split_dim = 0, + const std::optional>> + &full_shapes_arg = std::nullopt, + const ReplicateConfig &config = ReplicateConfig{}) { + if (base_keys.size() != tensor_chunks.size()) { + if (!base_keys.empty()) LOG(ERROR) << "Size mismatch in batch_put"; + return std::vector(base_keys.size(), + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + + if (full_shapes_arg.has_value() && + full_shapes_arg->size() != base_keys.size()) { + LOG(ERROR) << "Size mismatch: full_shapes must match keys size"; + return std::vector(base_keys.size(), + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + + if (!is_client_initialized() || use_dummy_client_) { + LOG(ERROR) << "Client not initialized or Dummy client not " + "supported for tensors"; + return std::vector(base_keys.size(), + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + + if (tp_size <= 1) { + return batch_put_tensor_impl(base_keys, tensor_chunks, config); + } + + if (tp_rank < 0 || tp_rank >= tp_size) { + LOG(ERROR) << "Invalid put_tp_rank: " << tp_rank + << ", must be in range [0, " << tp_size << ")"; + return std::vector(base_keys.size(), + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + + const size_t num_keys = base_keys.size(); + if (num_keys == 0) { + return std::vector(); + } + + std::vector results(num_keys, 0); + std::vector infos(num_keys); + std::vector contiguous_tensors; + contiguous_tensors.reserve(num_keys); + + for (size_t i = 0; i < num_keys; ++i) { + pybind11::object tensor_chunk = tensor_chunks[i].cast(); + + if (!tensor_chunk.attr("is_contiguous")().cast()) { + tensor_chunk = tensor_chunk.attr("contiguous")(); + } + contiguous_tensors.push_back(tensor_chunk); + + infos[i] = extract_tensor_info(tensor_chunk, base_keys[i]); + if (!infos[i].valid()) { + results[i] = to_py_ret(ErrorCode::INVALID_PARAMS); + } + } + + std::vector> full_shapes(num_keys); + for (size_t i = 0; i < num_keys; ++i) { + if (!infos[i].valid()) continue; + + std::optional> single_full_shape_arg; + if (full_shapes_arg.has_value()) { + single_full_shape_arg = (*full_shapes_arg)[i]; + } + try { + calculate_full_shape(infos[i].metadata, split_dim, tp_size, + single_full_shape_arg, + full_shapes[i].data()); + validate_chunk_matches_tp_plan(infos[i].metadata, + full_shapes[i].data(), split_dim, + tp_rank, tp_size); + } catch (const std::exception &e) { + LOG(ERROR) << "Provided full_shape dim mismatch for key: " + << base_keys[i]; + results[i] = to_py_ret(ErrorCode::INVALID_PARAMS); + } + } + + std::vector chunk_keys; + pybind11::list valid_chunks; + std::vector valid_indices; + for (size_t i = 0; i < num_keys; ++i) { + if (infos[i].valid() && results[i] == 0) { + chunk_keys.push_back(get_tp_key_name(base_keys[i], tp_rank)); + valid_chunks.append(contiguous_tensors[i]); + valid_indices.push_back(i); + } + } + + if (!valid_chunks.empty()) { + std::vector chunk_put_results = + batch_put_tensor_impl(chunk_keys, valid_chunks, config); + for (size_t j = 0; j < valid_indices.size(); ++j) { + results[valid_indices[j]] = chunk_put_results[j]; + } + } + + std::vector chunk_put_status = results; + + std::vector chunk_meta_keys; + std::vector chunk_meta_buffers; + std::vector chunk_meta_sizes; + std::vector chunk_meta_indices; + std::vector chunk_meta_storage; + chunk_meta_storage.reserve(num_keys); + + for (size_t i = 0; i < num_keys; ++i) { + if (!infos[i].valid() || results[i] != 0) continue; + + int64_t dim_size = full_shapes[i][split_dim]; + auto [start_idx, calculated_size] = + calculate_chunk_range(dim_size, tp_rank, tp_size); + (void)calculated_size; + int64_t chunk_size = infos[i].metadata.shape[split_dim]; + + chunk_meta_storage.push_back(ChunkMetadata{start_idx, chunk_size}); + + chunk_meta_keys.push_back( + get_chunk_meta_key_name(base_keys[i], tp_rank)); + chunk_meta_buffers.push_back(&chunk_meta_storage.back()); + chunk_meta_sizes.push_back(sizeof(ChunkMetadata)); + chunk_meta_indices.push_back(i); + } + + batch_put_metadata_and_update_results( + store_.get(), chunk_meta_keys, chunk_meta_buffers, chunk_meta_sizes, + chunk_meta_indices, results, config); + + if (tp_rank == 0) { + std::vector global_meta_keys; + std::vector global_meta_buffers; + std::vector global_meta_sizes; + std::vector global_meta_indices; + std::vector global_meta_storage; + global_meta_storage.reserve(num_keys); + + for (size_t i = 0; i < num_keys; ++i) { + if (!infos[i].valid() || results[i] != 0) continue; + + global_meta_storage.push_back( + create_global_metadata(infos[i].metadata, split_dim, + tp_size, full_shapes[i].data())); + + global_meta_keys.push_back( + get_global_meta_key_name(base_keys[i])); + global_meta_buffers.push_back(&global_meta_storage.back()); + global_meta_sizes.push_back(sizeof(GlobalMetadata)); + global_meta_indices.push_back(i); + } + + batch_put_metadata_and_update_results( + store_.get(), global_meta_keys, global_meta_buffers, + global_meta_sizes, global_meta_indices, results, config); + } + + cleanup_partial_tp_chunk_puts(store_.get(), base_keys, results, tp_rank, + tp_rank == 0); + for (size_t i = 0; i < num_keys; ++i) { + if (chunk_put_status[i] != 0 && results[i] == 0) { + results[i] = chunk_put_status[i]; + } + } + + return results; + } + std::vector batch_put_tensor_with_tp( const std::vector &base_keys, const pybind11::list &tensors_list, int tp_rank = 0, int tp_size = 1, @@ -864,28 +1401,235 @@ class MooncakeStorePyWrapper { << "put_tensor_with_tp_from is not supported for dummy client"; return to_py_ret(ErrorCode::INVALID_PARAMS); } - if (buffer_ptr == 0) { - LOG(ERROR) << "Buffer pointer cannot be null"; + if (tp_size <= 1) { + return put_tensor_from(key, buffer_ptr, size); + } + py::object tensor = decode_serialized_tensor_buffer( + buffer_ptr, size, "put_tensor_with_tp_from"); + if (tensor.is_none()) { return to_py_ret(ErrorCode::INVALID_PARAMS); } - if (size <= sizeof(TensorMetadata)) { - LOG(ERROR) << "Buffer size too small for tensor metadata"; + return put_tensor_with_tp_impl(key, tensor, ReplicateConfig{}, tp_rank, + tp_size, split_dim); + } + + int put_tensor_chunk_with_tp_from( + const std::string &key, uintptr_t buffer_ptr, size_t size, int tp_rank, + int tp_size = 1, int split_dim = 0, + const std::optional> &full_shape_arg = + std::nullopt, + const ReplicateConfig &config = ReplicateConfig{}) { + if (!is_client_initialized()) { + LOG(ERROR) << "Client is not initialized"; + return to_py_ret(ErrorCode::INVALID_PARAMS); + } + if (use_dummy_client_) { + LOG(ERROR) << "put_tensor_chunk_with_tp_from is not supported for " + "dummy client"; return to_py_ret(ErrorCode::INVALID_PARAMS); } if (tp_size <= 1) { return put_tensor_from(key, buffer_ptr, size); } + if (buffer_ptr == 0 || size <= sizeof(TensorMetadata)) { + LOG(ERROR) << "Invalid buffer for put_tensor_chunk_with_tp_from"; + return to_py_ret(ErrorCode::INVALID_PARAMS); + } + if (tp_rank < 0 || tp_rank >= tp_size) { + LOG(ERROR) << "Invalid tp_rank: " << tp_rank; + return to_py_ret(ErrorCode::INVALID_PARAMS); + } - pybind11::object tensor = - buffer_to_tensor(NULL, reinterpret_cast(buffer_ptr), - static_cast(size)); - if (tensor.is_none()) { - LOG(ERROR) << "Failed to decode full tensor buffer for " - "put_tensor_with_tp_from"; + TensorMetadata tensor_meta; + memcpy(&tensor_meta, reinterpret_cast(buffer_ptr), + sizeof(TensorMetadata)); + + int64_t full_shape[4] = {0}; + try { + calculate_full_shape(tensor_meta, split_dim, tp_size, + full_shape_arg, full_shape); + validate_chunk_matches_tp_plan(tensor_meta, full_shape, split_dim, + tp_rank, tp_size); + } catch (const std::exception &e) { + LOG(ERROR) << e.what(); return to_py_ret(ErrorCode::INVALID_PARAMS); } - return put_tensor_with_tp_impl(key, tensor, ReplicateConfig{}, tp_rank, - tp_size, split_dim); + + std::string tp_key = get_tp_key_name(key, tp_rank); + int ret; + { + py::gil_scoped_release release_gil; + ret = store_->put_from(tp_key, reinterpret_cast(buffer_ptr), + size, config); + } + if (ret != 0) return ret; + + ret = store_tensor_tp_metadata(key, tp_rank, tp_size, split_dim, + tensor_meta, full_shape, config); + if (ret != 0) { + store_->remove(tp_key); + return ret; + } + + return 0; + } + + std::vector batch_put_tensor_chunk_with_tp_from( + const std::vector &base_keys, + const std::vector &buffer_ptrs, + const std::vector &sizes, int tp_rank, int tp_size = 1, + int split_dim = 0, + const std::optional>> + &full_shapes_arg = std::nullopt, + const ReplicateConfig &config = ReplicateConfig{}) { + if (base_keys.size() != buffer_ptrs.size() || + base_keys.size() != sizes.size()) { + LOG(ERROR) + << "Size mismatch in batch_put_tensor_chunk_with_tp_from"; + return std::vector(base_keys.size(), + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + if (!is_client_initialized()) { + LOG(ERROR) << "Client is not initialized"; + return std::vector(base_keys.size(), + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + if (use_dummy_client_) { + LOG(ERROR) << "batch_put_tensor_chunk_with_tp_from is not " + "supported for dummy client"; + return std::vector(base_keys.size(), + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + if (tp_size <= 1) { + return batch_put_tensor_from(base_keys, buffer_ptrs, sizes); + } + if (tp_rank < 0 || tp_rank >= tp_size) { + LOG(ERROR) << "Invalid tp_rank: " << tp_rank; + return std::vector(base_keys.size(), + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + if (full_shapes_arg.has_value() && + full_shapes_arg->size() != base_keys.size()) { + LOG(ERROR) << "Size mismatch: full_shapes must match keys size"; + return std::vector(base_keys.size(), + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + + const size_t num_keys = base_keys.size(); + if (num_keys == 0) return std::vector(); + + for (size_t i = 0; i < num_keys; ++i) { + if (buffer_ptrs[i] == 0 || sizes[i] <= sizeof(TensorMetadata)) { + LOG(ERROR) << "Invalid buffer at index " << i; + return std::vector(num_keys, + to_py_ret(ErrorCode::INVALID_PARAMS)); + } + } + + std::vector chunk_keys; + chunk_keys.reserve(num_keys); + for (const auto &key : base_keys) { + chunk_keys.push_back(get_tp_key_name(key, tp_rank)); + } + std::vector results; + { + py::gil_scoped_release release_gil; + results = store_->batch_put_from( + chunk_keys, CastAddrs2Ptrs(buffer_ptrs), sizes, config); + } + + std::vector chunk_put_status = results; + std::vector tensor_metas(num_keys); + std::vector> full_shapes(num_keys); + + for (size_t i = 0; i < num_keys; ++i) { + if (results[i] != 0) continue; + memcpy(&tensor_metas[i], + reinterpret_cast(buffer_ptrs[i]), + sizeof(TensorMetadata)); + + std::optional> single_full_shape; + if (full_shapes_arg.has_value()) { + single_full_shape = (*full_shapes_arg)[i]; + } + try { + calculate_full_shape(tensor_metas[i], split_dim, tp_size, + single_full_shape, full_shapes[i].data()); + validate_chunk_matches_tp_plan(tensor_metas[i], + full_shapes[i].data(), split_dim, + tp_rank, tp_size); + } catch (const std::exception &e) { + LOG(ERROR) << e.what(); + results[i] = to_py_ret(ErrorCode::INVALID_PARAMS); + } + } + + size_t valid_count = 0; + for (size_t i = 0; i < num_keys; ++i) { + if (results[i] == 0) valid_count++; + } + + std::vector chunk_meta_storage; + std::vector chunk_meta_keys; + std::vector chunk_meta_buffers; + std::vector chunk_meta_sizes; + std::vector chunk_meta_indices; + chunk_meta_storage.reserve(valid_count); + + for (size_t i = 0; i < num_keys; ++i) { + if (results[i] != 0) continue; + int64_t dim_size = full_shapes[i][split_dim]; + auto [start_idx, calculated_size] = + calculate_chunk_range(dim_size, tp_rank, tp_size); + (void)calculated_size; + int64_t chunk_size = tensor_metas[i].shape[split_dim]; + + chunk_meta_storage.push_back(ChunkMetadata{start_idx, chunk_size}); + chunk_meta_keys.push_back( + get_chunk_meta_key_name(base_keys[i], tp_rank)); + chunk_meta_buffers.push_back(&chunk_meta_storage.back()); + chunk_meta_sizes.push_back(sizeof(ChunkMetadata)); + chunk_meta_indices.push_back(i); + } + + batch_put_metadata_and_update_results( + store_.get(), chunk_meta_keys, chunk_meta_buffers, chunk_meta_sizes, + chunk_meta_indices, results, config); + + if (tp_rank == 0) { + std::vector global_meta_storage; + std::vector global_meta_keys; + std::vector global_meta_buffers; + std::vector global_meta_sizes; + std::vector global_meta_indices; + global_meta_storage.reserve(valid_count); + + for (size_t i = 0; i < num_keys; ++i) { + if (results[i] != 0) continue; + global_meta_storage.push_back( + create_global_metadata(tensor_metas[i], split_dim, tp_size, + full_shapes[i].data())); + global_meta_keys.push_back( + get_global_meta_key_name(base_keys[i])); + global_meta_buffers.push_back(&global_meta_storage.back()); + global_meta_sizes.push_back(sizeof(GlobalMetadata)); + global_meta_indices.push_back(i); + } + + batch_put_metadata_and_update_results( + store_.get(), global_meta_keys, global_meta_buffers, + global_meta_sizes, global_meta_indices, results, config); + } + + cleanup_partial_tp_chunk_puts(store_.get(), base_keys, results, tp_rank, + tp_rank == 0); + for (size_t i = 0; i < num_keys; ++i) { + if (chunk_put_status[i] != 0 && results[i] == 0) { + results[i] = chunk_put_status[i]; + } + } + + return results; } std::vector batch_put_tensor_with_tp_from( @@ -916,31 +1660,16 @@ class MooncakeStorePyWrapper { return std::vector(base_keys.size(), to_py_ret(ErrorCode::INVALID_PARAMS)); } - py::list tensors_list; std::vector processed_indices; std::vector final_results(base_keys.size(), 0); for (size_t i = 0; i < base_keys.size(); ++i) { - if (buffer_ptrs[i] == 0) { - LOG(ERROR) << "Buffer pointer at index " << i - << " cannot be null"; - final_results[i] = to_py_ret(ErrorCode::INVALID_PARAMS); - continue; - } - if (sizes[i] <= sizeof(TensorMetadata)) { - LOG(ERROR) << "Buffer size at index " << i - << " too small for tensor metadata"; - final_results[i] = to_py_ret(ErrorCode::INVALID_PARAMS); - continue; - } - - py::object tensor = - buffer_to_tensor(NULL, reinterpret_cast(buffer_ptrs[i]), - static_cast(sizes[i])); + py::object tensor = decode_serialized_tensor_buffer( + buffer_ptrs[i], sizes[i], + "batch_put_tensor_with_tp_from buffer at index " + + std::to_string(i)); if (tensor.is_none()) { - LOG(ERROR) << "Failed to decode full tensor buffer at index " - << i; final_results[i] = to_py_ret(ErrorCode::INVALID_PARAMS); continue; } @@ -1760,6 +2489,22 @@ PYBIND11_MODULE(store, m) { py::arg("split_dim") = 0, "Put a batch of PyTorch tensors into the store, splitting each " "into shards for tensor parallelism.") + .def("put_tensor_chunk_with_tp", + &MooncakeStorePyWrapper::put_tensor_chunk_with_tp, py::arg("key"), + py::arg("tensor_chunk"), py::arg("tp_rank") = 0, + py::arg("tp_size") = 1, py::arg("split_dim") = 0, + py::arg("full_shape") = py::none(), + py::arg("config") = ReplicateConfig{}, + "Put one tensor-parallel shard and write ChunkMetadata plus " + "GlobalMetadata (rank 0 only).") + .def("batch_put_tensor_chunk_with_tp", + &MooncakeStorePyWrapper::batch_put_tensor_chunk_with_tp, + py::arg("base_keys"), py::arg("tensor_chunks"), + py::arg("tp_rank") = 0, py::arg("tp_size") = 1, + py::arg("split_dim") = 0, py::arg("full_shapes") = py::none(), + py::arg("config") = ReplicateConfig{}, + "Put a batch of tensor-parallel shards and write TP metadata for " + "each item.") .def("put_tensor", &MooncakeStorePyWrapper::put_tensor, py::arg("key"), py::arg("tensor"), "Put a PyTorch tensor into the store") .def("batch_get_tensor", &MooncakeStorePyWrapper::batch_get_tensor, @@ -1862,6 +2607,22 @@ PYBIND11_MODULE(store, m) { "Put a batch of full tensors directly from pre-allocated " "buffers for Tensor Parallelism. Each buffer is internally split " "and stored under key_tp_ for all ranks.") + .def("put_tensor_chunk_with_tp_from", + &MooncakeStorePyWrapper::put_tensor_chunk_with_tp_from, + py::arg("key"), py::arg("buffer_ptr"), py::arg("size"), + py::arg("tp_rank"), py::arg("tp_size") = 1, + py::arg("split_dim") = 0, py::arg("full_shape") = py::none(), + py::arg("config") = ReplicateConfig{}, + "Store a serialized tensor shard from a registered buffer and " + "write TP metadata.") + .def("batch_put_tensor_chunk_with_tp_from", + &MooncakeStorePyWrapper::batch_put_tensor_chunk_with_tp_from, + py::arg("base_keys"), py::arg("buffer_ptrs"), py::arg("sizes"), + py::arg("tp_rank"), py::arg("tp_size") = 1, + py::arg("split_dim") = 0, py::arg("full_shapes") = py::none(), + py::arg("config") = ReplicateConfig{}, + "Store a batch of serialized tensor shards from registered " + "buffers and write TP metadata.") .def("upsert_tensor", &MooncakeStorePyWrapper::upsert_tensor, py::arg("key"), py::arg("tensor"), "Upsert a PyTorch tensor into the store (insert or update)") diff --git a/scripts/test_tensor_api.py b/scripts/test_tensor_api.py index a0972d2af0..32c4491d29 100644 --- a/scripts/test_tensor_api.py +++ b/scripts/test_tensor_api.py @@ -598,6 +598,12 @@ def _print_perf(self, name, times): avg_gbps = (self.total_bits / 1e9) / avg_time print(f"👉 [Result] {name:30} | Avg Time: {avg_time:.4f}s | Throughput: {avg_gbps:.2f} Gbps") + def _print_payload_perf(self, name, times, payload_bytes): + avg_time = np.mean(times) + avg_gbps = ((payload_bytes * 8) / 1e9) / avg_time + print(f"👉 [Result] {name:30} | Avg Time: {avg_time * 1000:.2f} ms | Throughput: {avg_gbps:.2f} Gbps") + return avg_time, avg_gbps + def test_benchmark_01_batch_put_get(self): """Benchmark: Standard Batch Put/Get.""" put_times = [] @@ -775,6 +781,163 @@ def test_benchmark_04_batch_put_get_into_with_tp(self): for buf_info in rank_buffers: self.assertEqual(self.store.unregister_buffer(buf_info['base_ptr']), 0, "Buffer unregistration failed") + def test_benchmark_04_single_put_vs_chunk_put_with_warmup(self): + """Benchmark: compare put paths after sufficient warmup.""" + tp_size = 4 + split_dim = 0 + shard_sizes_mb = [256, 512, 1024] + warmup_rounds = 3 + iterations = 5 + + dtype_map = { + torch.float32: 0, + torch.float64: 1, + torch.int32: 2, + torch.int64: 3, + torch.int16: 4, + torch.int8: 5, + torch.uint8: 6, + torch.float16: 7, + torch.bool: 8, + torch.bfloat16: 9, + } + + for shard_size_mb in shard_sizes_mb: + num_elements = (shard_size_mb * 1024 * 1024) // 4 + rows = 1024 + cols = max(tp_size, num_elements // rows) + cols = (cols // tp_size) * tp_size + full_tensor = torch.randn(rows, cols, dtype=torch.float32).contiguous() + shard = full_tensor.chunk(tp_size, split_dim)[0].contiguous() + payload_bytes = serialized_tensor_size(shard) + put_times = [] + put_from_times = [] + chunk_put_times = [] + chunk_put_from_times = [] + + serialized_buffer = (ctypes.c_ubyte * payload_bytes)() + serialized_ptr = ctypes.addressof(serialized_buffer) + self.assertEqual(self.store.register_buffer(serialized_ptr, payload_bytes), 0) + try: + shape = list(shard.shape) + [-1] * (4 - shard.ndim) + import struct + struct.pack_into( + " 0 else 0.0 + throughput_delta = ((avg_gbps - base_gbps) / base_gbps) * 100 if base_gbps > 0 else 0.0 + print( + f"👉 [Compare] {shard_size_mb}MB shard | {name}: Latency delta {latency_delta:+.2f}% | Throughput delta {throughput_delta:+.2f}%" + ) + def test_benchmark_05_batch_pub_get(self): """Benchmark: Standard Batch Pub/Get.""" put_times = [] diff --git a/scripts/test_tensor_chunk_api.py b/scripts/test_tensor_chunk_api.py new file mode 100644 index 0000000000..05ac10def9 --- /dev/null +++ b/scripts/test_tensor_chunk_api.py @@ -0,0 +1,382 @@ +import argparse +import ctypes +import os +import sys +import unittest + +import torch + +from mooncake.mooncake_config import MooncakeConfig +from mooncake.store import MooncakeDistributedStore + + +TENSOR_METADATA_SIZE = 4 + 4 + 8 * 4 + + +def serialized_tensor_size(tensor): + return TENSOR_METADATA_SIZE + tensor.numel() * tensor.element_size() + + +GLOBAL_STORE = None +GLOBAL_CONFIG = None + + +def create_store_connection(): + store = MooncakeDistributedStore() + config = MooncakeConfig.load_from_env() + print( + f"[{os.getpid()}] Connecting to Mooncake Master at " + f"{config.master_server_address} using {config.protocol}..." + ) + rc = store.setup( + config.local_hostname, + config.metadata_server, + config.global_segment_size, + config.local_buffer_size, + config.protocol, + config.device_name, + config.master_server_address, + ) + if rc != 0: + raise RuntimeError(f"Failed to setup mooncake store, error code: {rc}") + return store, config + + +def setUpModule(): + global GLOBAL_STORE, GLOBAL_CONFIG + try: + GLOBAL_STORE, GLOBAL_CONFIG = create_store_connection() + print("✅ Global Store connection established.") + except Exception as e: + print(f"❌ Failed to establish global store connection: {e}") + sys.exit(1) + + +def tearDownModule(): + global GLOBAL_STORE + if GLOBAL_STORE: + print("\nClosing global store connection...") + GLOBAL_STORE.close() + GLOBAL_STORE = None + + +class MooncakeTestBase(unittest.TestCase): + def setUp(self): + if GLOBAL_STORE is None: + self.skipTest("Store not initialized") + self.store = GLOBAL_STORE + self.config = GLOBAL_CONFIG + self.store.remove_all() + + +class TestTensorChunkAPI(MooncakeTestBase): + def test_put_tensor_chunk_with_tp_invalid_split_dim(self): + key = "chunk_invalid_split_dim" + chunk = torch.arange(16, dtype=torch.float32).reshape(4, 4) + + rc = self.store.put_tensor_chunk_with_tp( + key, + chunk, + tp_rank=0, + tp_size=2, + split_dim=2, + full_shape=[8, 4], + ) + self.assertNotEqual(rc, 0) + self.assertEqual(self.store.is_exist(f"{key}_tp_0"), 0) + self.assertEqual(self.store.is_exist(f"{key}_tp_0_meta"), 0) + self.assertEqual(self.store.is_exist(f"{key}_global_meta"), 0) + + def test_put_tensor_chunk_with_tp_rejects_mismatched_chunk_shape(self): + key = "chunk_invalid_plan" + chunk = torch.arange(12, dtype=torch.float32).reshape(3, 4) + + rc = self.store.put_tensor_chunk_with_tp( + key, + chunk, + tp_rank=0, + tp_size=2, + split_dim=0, + full_shape=[8, 4], + ) + self.assertNotEqual(rc, 0) + self.assertEqual(self.store.is_exist(f"{key}_tp_0"), 0) + self.assertEqual(self.store.is_exist(f"{key}_tp_0_meta"), 0) + self.assertEqual(self.store.is_exist(f"{key}_global_meta"), 0) + + def test_put_tensor_chunk_with_tp_writes_metadata_and_shard(self): + key = "chunk_test_single" + tensor = torch.arange(32, dtype=torch.float32).reshape(8, 4) + tp_size = 4 + split_dim = 0 + chunks = tensor.chunk(tp_size, split_dim) + + for rank, chunk in enumerate(chunks): + rc = self.store.put_tensor_chunk_with_tp( + key, + chunk, + tp_rank=rank, + tp_size=tp_size, + split_dim=split_dim, + full_shape=list(tensor.shape), + ) + self.assertEqual(rc, 0) + + shard = self.store.get_tensor(f"{key}_tp_{rank}") + self.assertTrue(torch.equal(shard, chunk)) + self.assertEqual(self.store.is_exist(f"{key}_tp_{rank}_meta"), 1) + + self.assertEqual(self.store.is_exist(f"{key}_global_meta"), 1) + + chunk_meta = self.store.get(f"{key}_tp_2_meta") + self.assertEqual(len(chunk_meta), 16) + start_idx = int.from_bytes(chunk_meta[:8], byteorder="little", signed=True) + shard_size = int.from_bytes(chunk_meta[8:16], byteorder="little", signed=True) + self.assertEqual(start_idx, 4) + self.assertEqual(shard_size, 2) + + global_meta = self.store.get(f"{key}_global_meta") + self.assertEqual(len(global_meta), 48) + split_dim_meta = int.from_bytes(global_meta[8:12], byteorder="little", signed=True) + put_tp_size = int.from_bytes(global_meta[12:16], byteorder="little", signed=True) + dim0 = int.from_bytes(global_meta[16:24], byteorder="little", signed=True) + dim1 = int.from_bytes(global_meta[24:32], byteorder="little", signed=True) + self.assertEqual(split_dim_meta, split_dim) + self.assertEqual(put_tp_size, tp_size) + self.assertEqual((dim0, dim1), tensor.shape) + + fast_path = self.store.get_tensor_with_tp( + key, tp_rank=2, tp_size=tp_size, split_dim=split_dim + ) + self.assertTrue(torch.equal(fast_path, chunks[2])) + + def test_batch_put_tensor_chunk_with_tp_writes_all_metadata(self): + keys = ["chunk_batch_0", "chunk_batch_1"] + tensors = [ + torch.arange(24, dtype=torch.float32).reshape(6, 4), + torch.arange(48, dtype=torch.float32).reshape(6, 8), + ] + tp_rank = 1 + tp_size = 2 + split_dim = 1 + chunks = [tensor.chunk(tp_size, split_dim)[tp_rank].contiguous() for tensor in tensors] + full_shapes = [list(tensor.shape) for tensor in tensors] + + rc = self.store.batch_put_tensor_chunk_with_tp( + keys, + chunks, + tp_rank=tp_rank, + tp_size=tp_size, + split_dim=split_dim, + full_shapes=full_shapes, + ) + self.assertEqual(rc, [0, 0]) + + for key, chunk in zip(keys, chunks): + shard = self.store.get_tensor(f"{key}_tp_{tp_rank}") + self.assertTrue(torch.equal(shard, chunk)) + self.assertEqual(self.store.is_exist(f"{key}_tp_{tp_rank}_meta"), 1) + self.assertEqual(self.store.is_exist(f"{key}_global_meta"), 0) + + def test_batch_put_tensor_chunk_with_tp_rejects_mismatched_chunk_shape(self): + keys = ["chunk_bad_batch_0", "chunk_bad_batch_1"] + chunks = [ + torch.arange(12, dtype=torch.float32).reshape(3, 4), + torch.arange(12, dtype=torch.float32).reshape(3, 4), + ] + + rc = self.store.batch_put_tensor_chunk_with_tp( + keys, + chunks, + tp_rank=0, + tp_size=2, + split_dim=0, + full_shapes=[[8, 4], [8, 4]], + ) + self.assertNotEqual(rc, [0, 0]) + for key in keys: + self.assertEqual(self.store.is_exist(f"{key}_tp_0"), 0) + self.assertEqual(self.store.is_exist(f"{key}_tp_0_meta"), 0) + self.assertEqual(self.store.is_exist(f"{key}_global_meta"), 0) + + def test_rank_zero_batch_put_tensor_chunk_with_tp_writes_global_metadata(self): + keys = ["chunk_batch_rank0_0", "chunk_batch_rank0_1"] + tensors = [ + torch.arange(60, dtype=torch.float32).reshape(5, 12), + torch.arange(80, dtype=torch.float32).reshape(5, 16), + ] + tp_rank = 0 + tp_size = 4 + split_dim = 1 + chunks = [tensor.chunk(tp_size, split_dim)[tp_rank].contiguous() for tensor in tensors] + full_shapes = [list(tensor.shape) for tensor in tensors] + + rc = self.store.batch_put_tensor_chunk_with_tp( + keys, + chunks, + tp_rank=tp_rank, + tp_size=tp_size, + split_dim=split_dim, + full_shapes=full_shapes, + ) + self.assertEqual(rc, [0, 0]) + + for key in keys: + self.assertEqual(self.store.is_exist(f"{key}_tp_{tp_rank}_meta"), 1) + self.assertEqual(self.store.is_exist(f"{key}_global_meta"), 1) + + def test_put_tensor_chunk_with_tp_from_rejects_mismatched_chunk_shape(self): + key = "chunk_from_invalid_plan" + chunk = torch.arange(12, dtype=torch.float32).reshape(3, 4) + + seed_key = f"{key}_seed" + self.assertEqual(self.store.put_tensor(seed_key, chunk), 0) + size = serialized_tensor_size(chunk) + payload = (ctypes.c_ubyte * size)() + addr = ctypes.addressof(payload) + self.assertEqual(self.store.register_buffer(addr, size), 0) + copied = self.store.get_tensor_into(seed_key, addr, size) + self.assertIsNotNone(copied) + try: + rc = self.store.put_tensor_chunk_with_tp_from( + key, + addr, + size, + tp_rank=0, + tp_size=2, + split_dim=0, + full_shape=[8, 4], + ) + self.assertNotEqual(rc, 0) + finally: + self.store.unregister_buffer(addr) + + self.assertEqual(self.store.is_exist(f"{key}_tp_0"), 0) + self.assertEqual(self.store.is_exist(f"{key}_tp_0_meta"), 0) + self.assertEqual(self.store.is_exist(f"{key}_global_meta"), 0) + + def test_put_tensor_chunk_with_tp_from_stores_serialized_shard(self): + key = "chunk_from_single" + full_tensor = torch.arange(30, dtype=torch.float32).reshape(5, 6) + tp_rank = 1 + tp_size = 3 + split_dim = 1 + chunk = full_tensor.chunk(tp_size, split_dim)[tp_rank].contiguous() + + seed_key = f"{key}_seed" + self.assertEqual(self.store.put_tensor(seed_key, chunk), 0) + size = serialized_tensor_size(chunk) + payload = (ctypes.c_ubyte * size)() + addr = ctypes.addressof(payload) + self.assertEqual(self.store.register_buffer(addr, size), 0) + copied = self.store.get_tensor_into(seed_key, addr, size) + self.assertIsNotNone(copied) + try: + rc = self.store.put_tensor_chunk_with_tp_from( + key, + addr, + size, + tp_rank=tp_rank, + tp_size=tp_size, + split_dim=split_dim, + full_shape=list(full_tensor.shape), + ) + self.assertEqual(rc, 0) + finally: + self.store.unregister_buffer(addr) + + shard = self.store.get_tensor(f"{key}_tp_{tp_rank}") + self.assertTrue(torch.equal(shard, chunk)) + self.assertEqual(self.store.is_exist(f"{key}_tp_{tp_rank}_meta"), 1) + + def test_batch_put_tensor_chunk_with_tp_from_rejects_mismatched_chunk_shape(self): + keys = ["chunk_from_bad_batch_0", "chunk_from_bad_batch_1"] + chunks = [ + torch.arange(12, dtype=torch.float32).reshape(3, 4), + torch.arange(12, dtype=torch.float32).reshape(3, 4), + ] + seed_keys = [f"{key}_seed" for key in keys] + sizes = [serialized_tensor_size(chunk) for chunk in chunks] + payloads = [(ctypes.c_ubyte * size)() for size in sizes] + ptrs = [ctypes.addressof(payload) for payload in payloads] + + for seed_key, chunk in zip(seed_keys, chunks): + self.assertEqual(self.store.put_tensor(seed_key, chunk), 0) + for ptr, size, seed_key in zip(ptrs, sizes, seed_keys): + self.assertEqual(self.store.register_buffer(ptr, size), 0) + copied = self.store.get_tensor_into(seed_key, ptr, size) + self.assertIsNotNone(copied) + try: + rc = self.store.batch_put_tensor_chunk_with_tp_from( + keys, + ptrs, + sizes, + tp_rank=0, + tp_size=2, + split_dim=0, + full_shapes=[[8, 4], [8, 4]], + ) + self.assertNotEqual(rc, [0, 0]) + finally: + for ptr in ptrs: + self.store.unregister_buffer(ptr) + + for key in keys: + self.assertEqual(self.store.is_exist(f"{key}_tp_0"), 0) + self.assertEqual(self.store.is_exist(f"{key}_tp_0_meta"), 0) + self.assertEqual(self.store.is_exist(f"{key}_global_meta"), 0) + + def test_batch_put_tensor_chunk_with_tp_from_writes_metadata(self): + keys = ["chunk_from_batch_0", "chunk_from_batch_1"] + full_tensors = [ + torch.arange(24, dtype=torch.float32).reshape(6, 4), + torch.arange(36, dtype=torch.float32).reshape(6, 6), + ] + tp_rank = 0 + tp_size = 2 + split_dim = 0 + chunks = [tensor.chunk(tp_size, split_dim)[tp_rank].contiguous() for tensor in full_tensors] + seed_keys = [f"{key}_seed" for key in keys] + sizes = [serialized_tensor_size(chunk) for chunk in chunks] + payloads = [(ctypes.c_ubyte * size)() for size in sizes] + ptrs = [ctypes.addressof(payload) for payload in payloads] + full_shapes = [list(tensor.shape) for tensor in full_tensors] + + for seed_key, chunk in zip(seed_keys, chunks): + self.assertEqual(self.store.put_tensor(seed_key, chunk), 0) + for ptr, size, seed_key in zip(ptrs, sizes, seed_keys): + self.assertEqual(self.store.register_buffer(ptr, size), 0) + copied = self.store.get_tensor_into(seed_key, ptr, size) + self.assertIsNotNone(copied) + try: + rc = self.store.batch_put_tensor_chunk_with_tp_from( + keys, + ptrs, + sizes, + tp_rank=tp_rank, + tp_size=tp_size, + split_dim=split_dim, + full_shapes=full_shapes, + ) + self.assertEqual(rc, [0, 0]) + finally: + for ptr in ptrs: + self.store.unregister_buffer(ptr) + + for key, chunk in zip(keys, chunks): + shard = self.store.get_tensor(f"{key}_tp_{tp_rank}") + self.assertTrue(torch.equal(shard, chunk)) + self.assertEqual(self.store.is_exist(f"{key}_tp_{tp_rank}_meta"), 1) + self.assertEqual(self.store.is_exist(f"{key}_global_meta"), 1) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--verbose", action="store_true", help="Run tests with verbose output") + args, remaining = parser.parse_known_args() + + sys.argv = [sys.argv[0]] + remaining + if args.verbose: + unittest.main(verbosity=2) + else: + unittest.main()