Skip to content
29 changes: 20 additions & 9 deletions tensorrt_llm/_torch/modules/dwdp/page_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,17 +166,19 @@ def __init__(
try:
handle = create_local_handle(self._page_size, device_id)
handles.append(handle)
except Exception as e:
except BaseException as e:
# Release every page made so far exactly once, here, as release() does: a
# page that fails to release is logged, so the others are still released and
# this allocation error stays the one raised; release() also marks the pool
# released, so __del__ does not release the handles again once the driver
# may have reused their values.
self._page_handles.append(handles)
self.release()
raise RuntimeError(
f"Failed to allocate page {page_idx} in slot {slot_idx}: {e}"
) from e
if isinstance(e, Exception):
raise RuntimeError(
f"Failed to allocate page {page_idx} in slot {slot_idx}: {e}"
) from e
raise
self._page_handles.append(handles)
logger.debug(
f"[PagePool] Allocated {num_pages} pages ({self._page_size} B each) "
Expand Down Expand Up @@ -340,11 +342,20 @@ def map_pages(
)

mappings = []
for i in range(num_pages_needed):
va = va_start + i * self._page_size
handle = self._page_handles[slot][page_offset + i]
map_handle(va, self._page_size, handle, offset=0)
mappings.append((va, self._page_size))
try:
for i in range(num_pages_needed):
va = va_start + i * self._page_size
handle = self._page_handles[slot][page_offset + i]
map_handle(va, self._page_size, handle, offset=0)
mappings.append((va, self._page_size))
except BaseException:
try:
self.unmap_pages(mappings)
except BaseException as unmap_error: # noqa: BLE001 - cleanup must never mask the original
Comment thread
zhaoyangwang-nvidia marked this conversation as resolved.
Resolved
logger.warning(
f"[PagePool] Failed to unmap partial pages during rollback: {unmap_error}"
)
raise

# NOTE: set_access is intentionally NOT called here.
# The caller (WeightBuffer._setup_layer) issues a single
Expand Down
16 changes: 11 additions & 5 deletions tensorrt_llm/_torch/modules/dwdp/weight_buffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,8 +349,13 @@ def create(

return buffer

except Exception:
buffer.release()
except BaseException:
try:
buffer.release()
except BaseException as release_error: # noqa: BLE001 - cleanup must never mask the original
logger.warning(
f"[WeightBuffer] Failed to release resources during rollback: {release_error}"
)
raise

@staticmethod
Expand Down Expand Up @@ -443,6 +448,9 @@ def _setup_layer(
mappings=[],
va_regions=[],
)
# Register before mapping any weight so release() tears down earlier
# weights in this layer if a later weight fails.
self._layer_states[layer_idx] = layer_state

# Track page pool offsets within the slot — each weight name allocates
# its own pages sequentially within the slot.
Expand Down Expand Up @@ -514,7 +522,7 @@ def _setup_layer(
device_id=self._device_id,
)

except Exception:
except BaseException:
# Best-effort cleanup on error
for va, size in all_mappings:
try:
Expand All @@ -538,8 +546,6 @@ def _setup_layer(
remote_slices = self._compute_remote_slices(full_tensor, layout, spec.num_experts)
layer_state.remote_slices[name] = remote_slices

self._layer_states[layer_idx] = layer_state

def _create_tensor_view(
self,
va: int,
Expand Down
141 changes: 135 additions & 6 deletions tests/unittest/_torch/modules/dwdp/test_dwdp_setup_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,16 +267,22 @@ def test_a_ring_larger_than_free_memory_is_refused_before_any_allocation(
assert (copy.needed_bytes, copy.slot_pages, copy.page_size) == (needed, (2,) * num_slots, PAGE)


@pytest.mark.parametrize(
"injected",
[RuntimeError("CUDA_ERROR_OUT_OF_MEMORY"), KeyboardInterrupt()],
ids=["error", "interrupt"],
)
def test_a_page_pool_allocation_failure_releases_every_handle_once(
monkeypatch: pytest.MonkeyPatch,
injected: BaseException,
) -> None:
"""Slot 1 page 2 fails: the 5 handles made so far are released once, ``__del__`` adds none."""
created, released = [], []

def create_local_handle(size: int, device_id: int) -> int:
assert (size, device_id) == (PAGE, 0)
if len(created) == 5:
raise RuntimeError("CUDA_ERROR_OUT_OF_MEMORY")
raise injected
created.append(1000 + len(created))
return created[-1]

Expand All @@ -285,12 +291,135 @@ def create_local_handle(size: int, device_id: int) -> int:
error = None
try:
PagePool([3 * PAGE, 3 * PAGE], 0, granularity=GRANULARITY, page_size=PAGE)
except RuntimeError as exc:
except BaseException as exc:
error = exc
assert str(error) == "Failed to allocate page 2 in slot 1: CUDA_ERROR_OUT_OF_MEMORY"
assert str(error.__cause__) == "CUDA_ERROR_OUT_OF_MEMORY"
# Drop the traceback, the last reference to the half-built pool: its __del__ runs now.
if isinstance(injected, Exception):
assert isinstance(error, RuntimeError)
assert str(error) == "Failed to allocate page 2 in slot 1: CUDA_ERROR_OUT_OF_MEMORY"
assert error.__cause__ is injected
else:
assert error is injected
# Already released inside __init__ before GC; dropping the tracebacks must not release again.
assert created == [1000, 1001, 1002, 1003, 1004]
assert sorted(released) == created
injected.__traceback__ = None
del error
gc.collect()
assert created == [1000, 1001, 1002, 1003, 1004]
assert sorted(released) == created


@pytest.mark.parametrize(
"injected",
[RuntimeError("post map failed on w2 page 1"), KeyboardInterrupt()],
ids=["error", "interrupt"],
)
def test_weight_buffer_mid_layer_failure_rolls_back_earlier_weights_and_partial_pages(
monkeypatch: pytest.MonkeyPatch,
injected: BaseException,
) -> None:
"""A failure on a later weight in the same layer must unmap and free earlier weights' VA
regions, any partially mapped pool pages, and all allocated page handles."""
# w1: 12 remote experts * 1 MiB = 12 MiB (1 pool page);
# w2: 12 remote experts * 2 MiB = 24 MiB (2 pool pages).
shapes = {"w1": (1024, 1024), "w2": (1024, 2048)}
specs = {
3: {
name: WeightSpec(
16, chunk_shape=(4, *shape), full_shape=(16, *shape), dtype=torch.uint8
)
for name, shape in shapes.items()
}
}
handles = MnnvlHandleSet(
handles={(3, "w1"): 101, (3, "w2"): 102},
sizes={(3, "w1"): 2 * GRANULARITY, (3, "w2"): 4 * GRANULARITY},
)

reserved, freed, mapped, unmapped = [], [], [], []
created_handles, released_handles = [], []
next_va = [0x1000_0000]
pool_map_calls = [0]

def fake_create_handle(_sz: int, _dev: int) -> int:
handle = 900 + len(created_handles)
created_handles.append(handle)
return handle

def fake_reserve(size: int, _gran: int) -> int:
va = next_va[0]
next_va[0] += size + GRANULARITY
reserved.append((va, size))
return va

def fake_map_handle(va: int, size: int, _handle: int, offset: int = 0) -> None:
mapped.append((va, size))

def fake_pool_map(va: int, size: int, _handle: int, offset: int = 0) -> None:
pool_map_calls[0] += 1
# Call 1: w1 post page 0; Call 2: w2 post page 0; Call 3: w2 post page 1 fails.
if pool_map_calls[0] == 3:
raise injected
mapped.append((va, size))

def fake_unmap(va: int, size: int) -> None:
unmapped.append((va, size))

monkeypatch.setattr(weight_buffer, "get_allocation_granularity", lambda *_a, **_k: GRANULARITY)
monkeypatch.setattr(weight_buffer, "_check_ring_fits", lambda *_a, **_k: (3, 0))
monkeypatch.setattr(page_pool, "get_allocation_granularity", lambda *_a, **_k: GRANULARITY)
monkeypatch.setattr(page_pool, "create_local_handle", fake_create_handle)
monkeypatch.setattr(page_pool, "release_handle", released_handles.append)
monkeypatch.setattr(page_pool, "map_handle", fake_pool_map)
monkeypatch.setattr(page_pool, "unmap_va", fake_unmap)
monkeypatch.setattr(weight_buffer, "reserve_va", fake_reserve)
monkeypatch.setattr(weight_buffer, "free_va", lambda va, sz: freed.append((va, sz)))
monkeypatch.setattr(weight_buffer, "map_handle", fake_map_handle)
monkeypatch.setattr(weight_buffer, "unmap_va", fake_unmap)
monkeypatch.setattr(weight_buffer, "set_access", lambda *_a, **_k: None)
monkeypatch.setattr(
weight_buffer,
"tensor_from_ptr",
lambda ptr, shape, dtype, device_id: torch.empty(shape, dtype=dtype),
)

with pytest.raises(type(injected)) as exc_info:
WeightBuffer.create(
layer_weight_specs=specs,
handles=handles,
local_start=0,
local_end=4,
dwdp_size=4,
device_id=0,
num_slots=2,
)

assert exc_info.value is injected

assert len(reserved) == 2
assert sorted(freed) == sorted(reserved)
# w1 mnnvl + w1 post page 0 + w2 mnnvl + w2 post page 0 (all 4 unmapped once)
assert len(mapped) == 4
assert sorted(unmapped) == sorted(mapped)
assert created_handles == [900, 901, 902]
assert sorted(released_handles) == created_handles

# A secondary failure (including KeyboardInterrupt) in PagePool.unmap_pages() or
# buffer.release() during rollback must not mask the original setup error.
for target, attr, rollback_error in (
(PagePool, "unmap_pages", KeyboardInterrupt()),
(WeightBuffer, "release", RuntimeError("release failed")),
(WeightBuffer, "release", KeyboardInterrupt()),
):
pool_map_calls[0] = 0
with patch.object(target, attr, MagicMock(side_effect=rollback_error)):
with pytest.raises(type(injected)) as masked_info:
WeightBuffer.create(
layer_weight_specs=specs,
handles=handles,
local_start=0,
local_end=4,
dwdp_size=4,
device_id=0,
num_slots=2,
)
assert masked_info.value is injected