Skip to content

Commit 3147b79

Browse files
committed
Reuse memory_pool
Signed-off-by: Hui Gao <[email protected]>
1 parent 9298f1b commit 3147b79

File tree

4 files changed

+106
-28
lines changed

4 files changed

+106
-28
lines changed

tensorrt_llm/_torch/memory_buffer_utils.py

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@
44

55
import torch
66

7+
from tensorrt_llm.logger import logger
8+
9+
from .utils import get_shared_pool
10+
711

812
@dataclass
913
class BufferBlock:
@@ -80,9 +84,22 @@ def get_buffer(self, tensor_shape: list[int], dtype: torch.dtype,
8084

8185
# No suitable buffer was found, so allocate a new one.
8286
# The new buffer is created with uint8 to represent raw bytes.
83-
new_buffer_tensor = torch.zeros((required_memory_size, ),
84-
device='cuda',
85-
dtype=torch.uint8)
87+
new_buffer_tensor = None
88+
try:
89+
with torch.cuda.memory.use_mem_pool(get_shared_pool()):
90+
new_buffer_tensor = torch.zeros((required_memory_size, ),
91+
device='cuda',
92+
dtype=torch.uint8)
93+
except Exception as ex:
94+
# Need to check if this is an OOM exception
95+
logger.debug(
96+
f"Exception happened to create tensor from given memory pool: {str{ex}}"
97+
)
98+
# if exception happens during allocating memory from
99+
new_buffer_tensor = torch.zeros((required_memory_size, ),
100+
device='cuda',
101+
dtype=torch.uint8)
102+
86103
new_block = BufferBlock(buffer=new_buffer_tensor,
87104
is_reserved=reserve_buffer)
88105

tensorrt_llm/_torch/pyexecutor/cuda_graph_runner.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,15 @@ def needs_capture(self, key: Tuple[int, int, int]):
194194

195195
return key not in self.graph_outputs
196196

197+
def get_graph_pool(self):
198+
"""Returns the CUDA memory pool used by this graph runner.
199+
200+
Returns:
201+
The CUDA memory pool associated with captured graphs, or None if
202+
no graphs have been captured yet.
203+
"""
204+
return self.memory_pool
205+
197206
def capture(self,
198207
key: Tuple[int, int, int],
199208
forward_fn: Callable,
@@ -255,6 +264,7 @@ def _setup_spec_decoding_and_forward(key: Tuple[int, int, int],
255264
capture_inputs)
256265
if postprocess_fn is not None:
257266
postprocess_fn(capture_inputs)
267+
258268
with torch.cuda.graph(graph, pool=self.memory_pool):
259269
output = _setup_spec_decoding_and_forward(
260270
key, forward_fn, capture_inputs)

tensorrt_llm/_torch/pyexecutor/model_engine.py

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@
4848
from ..speculative.mtp import SampleStateTensorsMTP
4949
from ..utils import (get_model_extra_attrs,
5050
set_per_request_piecewise_cuda_graph_flag,
51-
set_torch_compiling, with_model_extra_attrs)
51+
set_shared_mem_pool, set_torch_compiling,
52+
with_model_extra_attrs)
5253
from .config import PyTorchConfig
5354
from .config_utils import is_mla
5455
from .cuda_graph_runner import CUDAGraphRunner
@@ -2196,35 +2197,35 @@ def forward(
21962197
new_tensors_device, cache_indirection_buffer)
21972198

21982199
self.iter_counter += 1
2200+
with set_shared_mem_pool(self.cuda_graph_runner.get_graph_pool()):
2201+
if not maybe_graph:
2202+
# Fallback to eager execution if graph was not used
2203+
with MoeLoadBalancerIterContext(moe_load_balancer):
2204+
outputs = self._forward_step(inputs, gather_ids,
2205+
gather_context_logits)
2206+
else:
2207+
if self.cuda_graph_runner.needs_capture(key):
21992208

2200-
if not maybe_graph:
2201-
# Fallback to eager execution if graph was not used
2202-
with MoeLoadBalancerIterContext(moe_load_balancer):
2203-
outputs = self._forward_step(inputs, gather_ids,
2204-
gather_context_logits)
2205-
else:
2206-
if self.cuda_graph_runner.needs_capture(key):
2207-
2208-
def capture_forward_fn(inputs: Dict[str, Any]):
2209-
with MoeLoadBalancerIterContext(moe_load_balancer):
2210-
return self._forward_step(
2211-
inputs,
2212-
gather_ids=gather_ids,
2213-
gather_context_logits=gather_context_logits)
2209+
def capture_forward_fn(inputs: Dict[str, Any]):
2210+
with MoeLoadBalancerIterContext(moe_load_balancer):
2211+
return self._forward_step(
2212+
inputs,
2213+
gather_ids=gather_ids,
2214+
gather_context_logits=gather_context_logits)
22142215

2215-
def capture_postprocess_fn(inputs: Dict[str, Any]):
2216-
self._postprocess_inputs(inputs)
2216+
def capture_postprocess_fn(inputs: Dict[str, Any]):
2217+
self._postprocess_inputs(inputs)
22172218

2218-
self.cuda_graph_runner.capture(key, capture_forward_fn,
2219-
inputs,
2220-
capture_postprocess_fn)
2219+
self.cuda_graph_runner.capture(key, capture_forward_fn,
2220+
inputs,
2221+
capture_postprocess_fn)
22212222

2222-
# here we don't need to use context since cuda graph capture didn't run kernel.
2223-
# maybe we need a cleaner way to do this.
2224-
outputs = self.cuda_graph_runner.replay(key, inputs)
2225-
else:
2226-
with MoeLoadBalancerIterContext(moe_load_balancer):
2223+
# here we don't need to use context since cuda graph capture didn't run kernel.
2224+
# maybe we need a cleaner way to do this.
22272225
outputs = self.cuda_graph_runner.replay(key, inputs)
2226+
else:
2227+
with MoeLoadBalancerIterContext(moe_load_balancer):
2228+
outputs = self.cuda_graph_runner.replay(key, inputs)
22282229

22292230
self._execute_logit_post_processors(scheduled_requests, outputs)
22302231

tensorrt_llm/_torch/utils.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,3 +320,53 @@ def get_device_uuid(device_idx: int) -> str:
320320
property = torch.cuda.get_device_properties(device_idx)
321321
uuid = "GPU-" + str(property.uuid)
322322
return uuid
323+
324+
325+
_buffer_pool = None
326+
327+
328+
def set_shared_pool(buffer_pool):
329+
"""Sets the global memory pool for buffer allocation.
330+
331+
Args:
332+
buffer_pool: A CUDA memory pool object to use for allocations.
333+
"""
334+
global _buffer_pool
335+
_buffer_pool = buffer_pool
336+
337+
338+
def get_shared_pool():
339+
"""Retrieves the current global memory pool.
340+
341+
Returns:
342+
The current memory pool, or None if not set.
343+
"""
344+
global _buffer_pool
345+
return _buffer_pool
346+
347+
348+
@contextlib.contextmanager
349+
def set_shared_mem_pool(mem_pool) -> contextlib.AbstractContextManager:
350+
"""Temporarily sets a preferred memory pool and restores the previous one on exit.
351+
352+
This context manager allows temporarily switching to a different memory pool
353+
for CUDA graph operations, ensuring the original pool is restored even if
354+
an exception occurs.
355+
356+
Args:
357+
mem_pool: The memory pool to use within the context.
358+
359+
Yields:
360+
None
361+
362+
Example:
363+
>>> with set_shared_mem_pool(buffer_pool):
364+
... # Allocations within this block use buffer_pool
365+
... tensor = allocate_buffer(...)
366+
"""
367+
old_buffer_pool = get_shared_pool()
368+
set_shared_pool(mem_pool)
369+
try:
370+
yield
371+
finally:
372+
set_mem_pool(old_buffer_pool)

0 commit comments

Comments
 (0)