Skip to content

[RDT] Pre-allocate nixl memory pool - #61573

Merged
edoakes merged 25 commits into
ray-project:masterfrom
Tencent:nixl_mem_pool
May 12, 2026
Merged

edoakes merged 25 commits into
ray-project:masterfrom
Tencent:nixl_mem_pool

Conversation

@Chong-Li

@Chong-Li Chong-Li commented Mar 8, 2026 •

Copy link
Copy Markdown
Contributor

Description

This PR introduces a pre-allocated nixl memory pool (at sender-side) to improve RDT performance. With this feature, we don't have to register/deregister nixl memory for every transfer.

Some follow-ups:

  1. Currently, we're using envs to enable/disable this feature. It might be better to offer a python API like register_nixl_memory (extend it or introduce a new one).
  2. Maintain the reference count for every memory block in the pool for tensor level deduplication.
  3. Memory pool for receiver side.

Related issues

#60443

Additional information

charliecli added 2 commits March 6, 2026 17:13
@Chong-Li
Chong-Li requested a review from a team as a code owner March 8, 2026 13:47
Comment thread python/ray/_version.py Resolved

@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 pre-allocated memory pool for NIXL to optimize tensor transport by reducing memory registration overhead, utilizing a new MemoryPoolManager integrated into NixlTensorTransport. However, it introduces a potential Denial of Service (DoS) risk due to large default pool sizes not accounted for by the Ray scheduler, and a race condition during GPU memory copies that could lead to data corruption. Additionally, my review highlights areas for improving the efficiency of the memory allocation logic within the new pool manager and standardizing logging practices by replacing print calls with the logging module.

Comment thread python/ray/_private/ray_constants.py Resolved
@ray-gardener ray-gardener Bot added core Issues that should be addressed in Ray Core community-contribution Contributed by the community labels Mar 8, 2026
Signed-off-by: charliecli <[email protected]>
Comment thread python/ray/tests/rdt/test_rdt_nixl.py Resolved
Signed-off-by: charliecli <[email protected]>
@Chong-Li Chong-Li changed the title [WIP][RDT] Pre-allocate nixl memory pool [RDT] Pre-allocate nixl memory pool Mar 9, 2026
@Chong-Li Chong-Li changed the title [RDT] Pre-allocate nixl memory pool [RDT] Pre-allocate nixl memory pool (1/N) Mar 9, 2026
Signed-off-by: charliecli <[email protected]>

# Track free blocks using a first-fit allocator
# List of (offset, size) tuples for free blocks, sorted by offset
self._free_blocks: List[MemoryBlock] = [

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.

If we're already tracking free_blocks separately, why do we need an is_free attribute for the block itself?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed

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.

Don't think it got removed in your latest patch


# Try to allocate all blocks atomically.
allocations: List[Tuple[int, int]] = []
temp_free_blocks = [

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.

Feel like you don't really need the copy to temp_free_blocks here and can just iterate through free_blocks?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We're allocating multiple blocks atomically, so using a temp copy avoids any rollback if part of allocations fail.

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.

Yea that part makes sense, but I feel like you could still do the same without creating a temp copy? Like just iterating through free blocks once to see if there's enough space, then iterate through it again. Pretty much what you're doing now just without the copy.

else:
i += 1

def copy_to_pool(self, tensor: "torch.Tensor", offset: int) -> int:

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.

Is there any point to a user specifying offset? Feel like it's an abstraction leak, the user should just have control on what they want to copy in

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is the offset (allocated from a call of allocate_multiple) in the memory pool for the tensor to be copied in, not the offset of the tensor.

"""Registers the tensor's memory with NIXL and bumps the reference count so the memory region is never deregistered."""
self._add_tensor_descs([tensor])

def get_nixl_agent(self):

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.

feels weird to put this in the get_nixl_agent method, think a new public api might be better that takes in a size/device? That way you also don't need the env variables as well

@Chong-Li Chong-Li Mar 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I actually left three follow-ups (just as this one and the other two comments below) at the PR description, and I was planing to finish up with another PR. But it's up to you if you prefer implementing all of them here.

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.

Ah missed that comment sorry, would you mind implementing the first two follow ups (python API + reference count)? I'll do the follow up for the receiver side pool.

Signed-off-by: charliecli <[email protected]>
@Chong-Li
Chong-Li requested a review from Sparks0219 March 11, 2026 01:46
@Chong-Li

Chong-Li commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor Author

@Sparks0219 Hi Josh, let me know if you are ok with leaving the three TODOs (listed at the PR description) for a seperate PR. This PR could just focus on the memory pool itself.

@Chong-Li

Copy link
Copy Markdown
Contributor Author

Hi @Sparks0219 @stephanie-wang, any other suggestions?

Signed-off-by: charliecli <[email protected]>
@stephanie-wang stephanie-wang self-assigned this Apr 30, 2026
Comment thread python/ray/tests/rdt/test_rdt_nixl.py Outdated
meta1 = transport.extract_tensor_transport_metadata(obj_id1, [view_a, view_b])
ptr = base.untyped_storage().data_ptr()
pool = transport._memory_pool
assert pool.has_block(ptr)

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.

I'm a bit confused about when ptr is added to the pool? I thought the pool was just a separately allocated tensor?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ptr was added to the pool when calling extract_tensor_transport_metadata with [view_a, view_b] as the input. The pool is just a large pre-allocated tensor (all zeros), and extract_tensor_transport_metadata tries to find available slots from the pool for the input tensors.

return f"MemoryBlock(offset={self.offset}, size={self.size})"


class MemoryPoolManager:

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.

Can we add unit tests for this class?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

self._free_blocks: List[MemoryBlock] = [MemoryBlock(offset=0, size=pool_size)]

# Track allocated blocks by storage data pointer.
# Maps storage_data_ptr -> (offset, size) in the pool.

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.

Do we need the storage_data_ptr? Isn't that just self._pool_tensor.data_ptr + offset?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Storage_data_ptr is the address of user's tensor. We need that as the key for de-duplication, so we don't need to allocate twice from the pool for the same tensor.

t.device == self._memory_pool.get_pool_tensor().device
for t in rdt_object
)
and not any(self._tensor_memory_registered(t) for t in rdt_object)

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.

How can this happen? Would it only happen if the tensor was passed to Ray/Nixl before the memory pool was registered?

@Chong-Li Chong-Li May 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, that is the only case.

sizes: List of sizes to allocate in bytes.

Returns:
List of (offset, size) tuples if all allocations succeed, None otherwise.

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.

Why not just return List[torch.Tensor]?

Then you could also remove the copy_storage_to_pool_block. You could also just have this method directly take in the tensors to copy in and do the copy here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Just re-organized MemoryPoolManager. Now we have two private methods: _allocate_multiple and _free_multiple, they are only implementations for allocation/free algorithms (has nothing to do with tensor operations). For now, I'm just using a decreasing-order, first-fit algorithm, and may improve it if needed. The two public methods: allocate_for_tensors and free_tensors, do the additional tensor operations, de-duplication and rollback.

"""
return storage_ptr in self._allocated_blocks

def track_allocation(self, storage_ptr: int, offset: int, size: int) -> None:

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.

Why does this and untrack_allocation need to be separate from allocate_multiple and free_multiple? They seem like they could just be inlined into those methods.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

"""
return self._pool_tensor

def has_block(self, storage_ptr: int) -> bool:

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.

Should it be private?

@Chong-Li Chong-Li May 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Need this as a public API when de-dup tensors in _allocate_pool_xfer_descs.

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.

For API consistency, could you have this take in the user's tensor instead of a storage_ptr?

"""
self._allocated_blocks.pop(storage_ptr, None)

def return_blocks(self, storage_ptrs: List[int]) -> None:

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.

Why do we have both this and free_multiple? Can we just have one that takes in List[torch.Tensor]?

@Chong-Li Chong-Li May 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The class was re-organized, as stated above.

Signed-off-by: charliecli <[email protected]>
Signed-off-by: charliecli <[email protected]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 7db78b8. Configure here.

Signed-off-by: charliecli <[email protected]>
@Chong-Li
Chong-Li requested a review from stephanie-wang May 5, 2026 02:09

@stephanie-wang stephanie-wang 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.

Thanks, the cleanup and tests look great! Just left a few last comments.

"""
return self._pool_tensor

def has_block(self, storage_ptr: int) -> bool:

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.

For API consistency, could you have this take in the user's tensor instead of a storage_ptr?

@Chong-Li

Chong-Li commented May 7, 2026

Copy link
Copy Markdown
Contributor Author

The failed tests seem not related.

@Chong-Li
Chong-Li requested a review from stephanie-wang May 7, 2026 01:50
@Sparks0219 Sparks0219 added the go add ONLY when ready to merge, run all tests label May 11, 2026
@stephanie-wang
stephanie-wang enabled auto-merge (squash) May 12, 2026 18:02
@edoakes
edoakes disabled auto-merge May 12, 2026 20:01
@edoakes
edoakes merged commit 1900216 into ray-project:master May 12, 2026
5 checks passed
Lucas61000 pushed a commit to Lucas61000/ray that referenced this pull request May 15, 2026
## Description
This PR introduces a pre-allocated nixl memory pool (at sender-side) to
improve RDT performance. With this feature, we don't have to
register/deregister nixl memory for every transfer.

Some follow-ups:
1. Currently, we're using envs to enable/disable this feature. It might
be better to offer a python API like `register_nixl_memory` (extend it
or introduce a new one).
2. Maintain the reference count for every memory block in the pool for
tensor level deduplication.
3. Memory pool for receiver side.

## Related issues
ray-project#60443 

---------

Signed-off-by: charliecli <[email protected]>
Co-authored-by: charliecli <[email protected]>
alexandrplashchinsky pushed a commit to alexandrplashchinsky/ray-alex that referenced this pull request May 29, 2026
## Description
This PR introduces a pre-allocated nixl memory pool (at sender-side) to
improve RDT performance. With this feature, we don't have to
register/deregister nixl memory for every transfer.

Some follow-ups:
1. Currently, we're using envs to enable/disable this feature. It might
be better to offer a python API like `register_nixl_memory` (extend it
or introduce a new one).
2. Maintain the reference count for every memory block in the pool for
tensor level deduplication.
3. Memory pool for receiver side.

## Related issues
ray-project#60443

---------

Signed-off-by: charliecli <[email protected]>
Co-authored-by: charliecli <[email protected]>
Signed-off-by: Alexandr Plashchinsky <[email protected]>
Sparks0219 added a commit that referenced this pull request Nov 20, 2026
Follows up on #61573 with the receive side of the NIXL memory pool.

When the receiver has registered a pool with `register_nixl_memory_pool`
and passes no target buffers, `ray.get` reads the incoming tensors into
regions of the pool, which is registered with NIXL once, instead of
registering new buffers for every transfer. Once the transfer lands, the
tensors are copied out into ordinary tensors on the source's device
type, and the regions go straight back to the pool. The tensors you get
are independent of the pool, so the pool size bounds how much data can
be in flight at once, not how much received data you can hold. An
earlier version of this PR tied blocks to the returned tensors with
`weakref`, which broke when a view outlived the tensor, so it copies out
instead.

- `MemoryPoolManager.allocate_regions`, `copy_out_and_free` and
`free_blocks` make up the receive-side allocator. Regions start on
`_MAX_ALIGNMENT`, so the sender's packed layout decodes in place. The
pool now has a lock, since sends and receives use it from both the main
and `_ray_system` threads.
- A failed or abandoned receive gives its regions back only after its
transfer handle is released, including when that release waits for
`_finish_transfers` (#67389) to stop polling the handle.
- Every pool call runs with the cleanups that garbage collection
triggers deferred, as the cache lock already does, so a fetch request's
`__del__` can't deadlock on the pool's lock.
- An object with an empty tensor skips the receive pool: NIXL can't find
a zero-length descriptor inside a registered region
(`NIXL_ERR_NOT_FOUND`).
- With user target buffers the pool is bypassed, as before.

**Not a duplicate:** this is the receive-side follow-up to #61573.
Searching open PRs for the NIXL memory pool turns up #68142 (pool
statistics, which touches the same files but not the receive path) and
nothing else on the receive side.

**Tests** (4x T4, UCX with `UCX_TLS=^gdr_copy`, Ray nightly 2b3daa8
with this branch's `python/ray/experimental` and `python/ray/tests`
linked in):
- `pytest python/ray/tests/rdt/test_rdt_nixl.py
python/ray/tests/rdt/test_nixl_agent_lock.py
python/ray/tests/rdt/test_nixl_memory_pool.py`: 95 passed, 1 skipped
(`test_nixl_borrow_after_abort`, skipped on master).
- `pytest python/ray/tests/rdt/test_nixl_backend_selection.py
python/ray/tests/rdt/test_rdt_custom.py
python/ray/tests/rdt/test_rdt_gloo.py` (with the two unit files above):
101 passed, 1 skipped.
- Each new test fails with its fix reverted.

AI assistance (Claude Code) was used for this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: Joshua Lee <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community core Issues that should be addressed in Ray Core go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants