Repository navigation
[TRTLLM-14808][fix] MNNVL partial-allocation cleanup and warmup compile fix - #17077
Conversation
…le fix Fix MNNVL memory cleanup when an allocation fails partway (unmap mapped ranges, release imported/local handles, and free/restore a newly reserved VA range instead of leaking the partially-created mapping), and add a Kimi KDA pure-prefill warmup request so the optimized single-sequence K123 torch.compile variant is compiled during warmup instead of recompiling pathologically at evaluation start. Found during Kimi K3 bring-up; part of the feat/kimi_k3 -> main staging plan (Wave A). Co-authored-by: Pengbo Wang <[email protected]> Co-authored-by: Brian Nguyen (TensorRT) <[email protected]> Signed-off-by: Brian Nguyen <[email protected]>
|
/bot run |
|
PR_Github #62831 [ run ] triggered by Bot. Commit: |
WalkthroughThe changes improve MNNVL memory failure recovery and gate a 257-token Kimi attention warmup on general warmup availability. ChangesMNNVL memory recovery
Kimi attention warmup
Estimated code review effort: 3 (Moderate) | ~20 minutes Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tensorrt_llm/_mnnvl_utils.py (1)
216-292: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftAddress-reservation rollback isn't covered for failures before the mapping loop.
reserved_new_address/previous_address_stateare computed at lines 205-211 specifically to let this function free a newly reserved VA range and restore prior state on failure. That rollback is only implemented in the mapping-loopexceptat lines 335-348. IfcuMemCreate/cuMemExportToShareableHandle(lines 216-224) raise — there's no try/except around them at all — or if the handle-exchange step fails (existingexceptat lines 265-292), a freshly reserved VA range is leaked andcls.current_start_address/current_rank_stride/current_mem_offsetare left dangling on the orphaned reservation, which is exactly the leak class this PR is meant to close.🔧 Suggested approach
Factor the address-rollback logic into a small helper and invoke it from every failure path once a new address may have been reserved, e.g.:
+def _rollback_reserved_address(): + if reserved_new_address: + try: + device_ptr = cuda.CUdeviceptr(cls.current_start_address) + _check_cu_result( + cuda.cuMemAddressFree(device_ptr, comm_size * cls.current_rank_stride) + ) + except RuntimeError as e: + logger.warning("cuMemAddressFree failed during error cleanup: %s", e) + else: + ( + cls.current_start_address, + cls.current_rank_stride, + cls.current_mem_offset, + ) = previous_address_state + +try: + allocated_mem_handle = _check_cu_result(...) + exported_fabric_handle = _check_cu_result(...) +except RuntimeError: + _rollback_reserved_address() + raiseand call
_rollback_reserved_address()from the existingexcept Exception:block at line 265 as well.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tensorrt_llm/_mnnvl_utils.py` around lines 216 - 292, Factor the reserved-address cleanup for reserved_new_address and previous_address_state into a helper, such as _rollback_reserved_address, that restores cls.current_start_address, current_rank_stride, and current_mem_offset and releases the newly reserved VA range. Invoke this helper for failures from cuMemCreate/cuMemExportToShareableHandle and from the existing handle-exchange except block, while preserving the original exception and existing resource cleanup; reuse the same helper in the mapping-loop failure path.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@tensorrt_llm/_mnnvl_utils.py`:
- Around line 320-349: Replace the three cleanup-block `except Exception`
clauses in the `mapped_rank_ptrs`, `mem_handles`, and `reserved_new_address`
cleanup sections with `except RuntimeError`, preserving their existing warning
messages and cleanup flow.
In `@tensorrt_llm/_torch/pyexecutor/model_engine.py`:
- Around line 1484-1493: Gate the Kimi-specific warmup addition in the
surrounding warmup setup with can_run_general_warmup so it is skipped when
general context warmups are unsupported, including Helix CP. Preserve the
existing model_type check, token count, logging, and warmup request behavior
when the capability is available.
---
Outside diff comments:
In `@tensorrt_llm/_mnnvl_utils.py`:
- Around line 216-292: Factor the reserved-address cleanup for
reserved_new_address and previous_address_state into a helper, such as
_rollback_reserved_address, that restores cls.current_start_address,
current_rank_stride, and current_mem_offset and releases the newly reserved VA
range. Invoke this helper for failures from
cuMemCreate/cuMemExportToShareableHandle and from the existing handle-exchange
except block, while preserving the original exception and existing resource
cleanup; reuse the same helper in the mapping-loop failure path.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 7d8ac90a-5754-4883-a27c-0a3a312102e6
📒 Files selected for processing (2)
tensorrt_llm/_mnnvl_utils.pytensorrt_llm/_torch/pyexecutor/model_engine.py
|
PR_Github #62831 [ run ] completed with state
|
…w cleanup exception handling Address review feedback: the Kimi KDA prefill warmup request is a pure-context request and must respect the can_run_general_warmup gate; the MNNVL cleanup handlers only need to catch the RuntimeError raised by _check_cu_result. Signed-off-by: Brian Nguyen <[email protected]>
|
/bot run |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
tensorrt_llm/_mnnvl_utils.py (1)
205-211: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftExtend rollback to allocation and export failures.
The new VA reservation occurs before
cuMemCreate,cuMemExportToShareableHandle, and the PID/FD exchange, but address rollback exists only in the later mapping-phase handler at Lines 335-348. If any earlier operation fails, the reservation is not freed andcls.current_*remains advanced; export failure also leaves the allocated CUDA handle live. Put all post-reservation work under a common rollback path, restoring the previous state only aftercuMemAddressFreesucceeds.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tensorrt_llm/_mnnvl_utils.py` around lines 205 - 211, Extend the rollback scope in the allocation flow around previous_address_state and reserved_new_address to cover cuMemCreate, cuMemExportToShareableHandle, PID/FD exchange, and subsequent mapping work. On any post-reservation failure, release the reserved VA first, restore cls.current_start_address, cls.current_rank_stride, and cls.current_mem_offset only after cuMemAddressFree succeeds, and destroy any allocated CUDA memory handle when export or later operations fail.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@tensorrt_llm/_mnnvl_utils.py`:
- Around line 205-211: Extend the rollback scope in the allocation flow around
previous_address_state and reserved_new_address to cover cuMemCreate,
cuMemExportToShareableHandle, PID/FD exchange, and subsequent mapping work. On
any post-reservation failure, release the reserved VA first, restore
cls.current_start_address, cls.current_rank_stride, and cls.current_mem_offset
only after cuMemAddressFree succeeds, and destroy any allocated CUDA memory
handle when export or later operations fail.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 596bb193-a604-49d6-8bd1-62ee296db0ce
📒 Files selected for processing (2)
tensorrt_llm/_mnnvl_utils.pytensorrt_llm/_torch/pyexecutor/model_engine.py
|
PR_Github #62856 [ run ] triggered by Bot. Commit: |
22b5415 to
f8a4a5d
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
tensorrt_llm/_mnnvl_utils.py (2)
320-334: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winClose temporary pidfds after descriptor import.
The POSIX path opens
pidfdsat Lines 241-247, but mapping/access failures enter this cleanup without closing them. Repeated setup failures can therefore exhaust process file descriptors; close each pidfd oncepidfd_getfdcompletes, using an idempotent cleanup path.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tensorrt_llm/_mnnvl_utils.py` around lines 320 - 334, Update the POSIX descriptor-import flow around pidfd_getfd to close every temporary pidfd after descriptor import completes, including when mapping or access setup fails. Use an idempotent cleanup path so each pidfd is closed at most once, and integrate it with the existing exception cleanup around mapped_rank_ptrs and mem_handles.
205-211: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftMake address rollback complete across every failure window.
The new reservation mutates class state before allocation and mapping finish, but rollback is split across incomplete paths:
tensorrt_llm/_mnnvl_utils.py#L205-L211: includecuMemCreateand handle-export failures in the same VA cleanup scope.tensorrt_llm/_mnnvl_utils.py#L335-L348: restore or invalidate the snapshot even whencuMemAddressFreefails, and track any unreleased reservation.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tensorrt_llm/_mnnvl_utils.py` around lines 205 - 211, Update the reservation flow around the class state snapshot at lines 205-211 in tensorrt_llm/_mnnvl_utils.py so cuMemCreate and handle-export failures share the same VA cleanup and rollback scope. In the failure cleanup around lines 335-348, ensure the saved address state is restored or invalidated even if cuMemAddressFree fails, and record any reservation that remains unreleased so subsequent allocations cannot reuse it incorrectly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@tensorrt_llm/_mnnvl_utils.py`:
- Around line 320-334: Update the POSIX descriptor-import flow around
pidfd_getfd to close every temporary pidfd after descriptor import completes,
including when mapping or access setup fails. Use an idempotent cleanup path so
each pidfd is closed at most once, and integrate it with the existing exception
cleanup around mapped_rank_ptrs and mem_handles.
- Around line 205-211: Update the reservation flow around the class state
snapshot at lines 205-211 in tensorrt_llm/_mnnvl_utils.py so cuMemCreate and
handle-export failures share the same VA cleanup and rollback scope. In the
failure cleanup around lines 335-348, ensure the saved address state is restored
or invalidated even if cuMemAddressFree fails, and record any reservation that
remains unreleased so subsequent allocations cannot reuse it incorrectly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: c42cc125-4011-4b1b-8a6d-ff2e8b708419
📒 Files selected for processing (2)
tensorrt_llm/_mnnvl_utils.pytensorrt_llm/_torch/pyexecutor/model_engine.py
🚧 Files skipped from review as they are similar to previous changes (1)
- tensorrt_llm/_torch/pyexecutor/model_engine.py
|
Author notes (preserving context from the original PR description):
|
|
/bot run |
|
PR_Github #62875 [ run ] triggered by Bot. Commit: |
|
PR_Github #62856 [ run ] completed with state |
BowenFu
left a comment
There was a problem hiding this comment.
Verified on the regression axis and it holds. The success path of open_mnnvl_memory is unchanged — every rank still maps the same range with cuMemSetAccess following each cuMemMap, and the mem_handles handed to the caller are identical; the only reordering is assigning the local/remote handles before the map call. cuMemAddressFree(ptr, comm_size * current_rank_stride) matches the address_size that new_mnnvl_memory_address reserved exactly, and the rollback is safe precisely because nothing is published into allocated_map / address_refcnt until the loop completes. The warmup hunk is genuinely inert here — neither kimi_k3 nor kimi_linear exists as a model_type on main today, so nothing currently supported changes.
Two things I'm explicitly not blocking on:
The three cleanup logs use %s interpolation — logger.warning("cuMemUnmap failed during error cleanup: %s", e). tensorrt_llm.logger is warning(*msg) and joins str() of each argument with spaces (logger.py:267-281), so it doesn't substitute; those lines will print a literal %s followed by the error. Worth an f-string since they're the only diagnostic on that path.
More substantively: the description says the mock harness for open_mnnvl_memory (4 cases, including the VA-free-plus-rollback and the cleanup-failure-doesn't-mask-original one) passes, but it isn't in the diff. That's 53 lines of error-recovery that no existing test reaches and that a real failure will only exercise on multi-node NVLink. You've already written it and it's CPU-only by construction — please commit it.
One note for when the K3 model lands: the KDA warmup sits inside _run_attention_warmup, which returns early unless the metadata is TrtllmAttentionMetadata, and the forward runs under trtllm_gen_fmha_jit_warmup(). That couples an FLA/K123 compile warmup to the TRTLLM-Gen FMHA backend, so on any other attention backend it silently won't happen.
|
PR_Github #62875 [ run ] completed with state
|
|
/bot run |
|
PR_Github #62906 [ run ] triggered by Bot. Commit: |
|
PR_Github #62906 [ run ] completed with state
|
|
Closed the multi-node validation gap this description originally called out — no code changes, description updated with the details. Ran on two nodes in a single NVLink domain (8 ranks, FABRIC handle path), injecting a failure into
The control is the pre-change file from this PR's merge base, run on the same hardware in the same job, so the passing cases are attributable to the change and not the environment. Two corrections while I'm here:
The current red CI on this PR is a B300 |
|
/bot run |
|
PR_Github #63071 [ run ] triggered by Bot. Commit: |
|
PR_Github #63071 [ run ] completed with state |
|
/bot run |
|
PR_Github #63287 [ run ] triggered by Bot. Commit: |
|
PR_Github #63287 [ run ] completed with state
|
|
/bot run |
|
PR_Github #63295 [ run ] triggered by Bot. Commit: |
|
PR_Github #63295 [ run ] completed with state
|
|
/bot run |
|
PR_Github #63308 [ run ] triggered by Bot. Commit: |
|
PR_Github #63308 [ run ] completed with state
|
|
/bot run |
|
PR_Github #63313 [ run ] triggered by Bot. Commit: |
|
PR_Github #63313 [ run ] completed with state |
Dev Engineer Review
RuntimeErrorfailures, logs cleanup errors without masking the original exception, and restores the prior address state.kimi_k3/kimi_linearmodels to compile the optimized K123 variant, gated bycan_run_general_warmup.QA Engineer Review
No test changes.
Description
Ports commit
46289149bafromfeat/kimi_k3tomain(JIRA: TRTLLM-14808). Two fixes found during Kimi K3 bring-up; this is part of the feat/kimi_k3 -> main staging plan (Wave A).1. MNNVL partial-allocation cleanup (
tensorrt_llm/_mnnvl_utils.py)MnnvlMemory.open_mnnvl_memorypreviously leaked resources if the import/map/set-access loop failed partway (e.g.cuMemImportFromShareableHandlefailing for one remote rank): already-mapped ranges stayed mapped, the local and previously-imported handles were never released, and a freshly reserved VA range was leaked while the class address state pointed at the poisoned range. The loop is now wrapped so that on failure we:current_start_address/current_rank_stride/current_mem_offsetback to the previous state,2. Warmup compile fix (
tensorrt_llm/_torch/pyexecutor/model_engine.py)For Kimi KDA models (
model_typeinkimi_k3/kimi_linear), a one-token context warmup takes the NT < 4 FLA fallback and never compiles the optimized single-sequence K123 torch.compile variant, causing a pathological recompilation at the start of long evaluations. Warmup now adds a 257-token pure-prefill request (non-chunk-aligned, five chunks) that enters the pure K123 path. This hunk is guarded bymodel_typeand is inert onmainuntil the Kimi K3 model definition lands (later wave of the staging plan).Test Coverage
Multi-node hardware validation (run after the initial review, closing the gap noted below): two nodes in a single NVLink domain, 8 ranks, FABRIC handle path. Failure was injected into
cuMemImportFromShareableHandlepartway through the import/map loop — after at least one range is already mapped, and after allallgathercollectives, so ranks stay in step. Each scenario then requires that a subsequent allocation still succeeds and that every rank's slice is readable from every other rank.CUDA_ERROR_INVALID_VALUECUDA_ERROR_INVALID_VALUE— the partial mappings survive and the nextcuMemMaphits already-mapped addressesThe control is the pre-change file from this PR's merge base, run on the same hardware in the same job, and it reproduces the leak in both scenarios — so the passing cases are attributable to this change rather than to the environment.
Success path on the same setup: unaligned 4 MB, 30 MB, then 768 MB allocations, with offset bookkeeping asserted after each,
rank_stride == 1 GiBafter the large allocation, and cross-rank reads verified for all three.Other validation:
MnnvlMemory.open_mnnvl_memory(cuda driver / MPI comm / torch stubbed, FABRIC handle path, 4 ranks): success path bookkeeping, mid-loop import failure with fresh VA reservation (verifies reverse-order unmap, release of local + imported handles, VA free + address-state rollback), failure on a reused VA range (verifies the range is NOT freed and offset is untouched), and cleanup-failure-does-not-mask-original-error. All 4 pass on this branch; as a control, the 3 failure-path tests fail on unpatchedmain.pre-commit run(isort, yapf, ruff, ruff-format, codespell, etc.) passes on both files;py_compileclean.main(nokimi_k3/kimi_linearmodel type exists onmainyet). It was exercised on multi-node hardware during Kimi K3 bring-up onfeat/kimi_k3.Correction to an earlier claim in this description, and a finding worth flagging separately: I previously wrote that
tests/unittest/_torch/multi_gpu/test_mnnvl_memory.pycovers the success path on MNNVL-capable runners. That is not currently true, for a reason unrelated to this PR. The test buildsMapping(world_size, rank, gpus_per_node, tp_size=world_size), leavingmoe_tp_sizeat its-1default, which resolves toworld_size.MnnvlMemory.get_commsplits on(pp_rank * cp_size + cp_rank) * moe_tp_size + moe_tp_rank, so that color reduces to the global rank and every rank ends up in a singleton communicator; the strided tensor then has one segment and the test raisesIndexErrorat line 68 for every rank > 0. I confirmed this on the hardware above — it fails identically with and without this PR's change, before reaching any of the modified code. The file is not referenced by any list undertests/integration/test_lists/test-db/, which is consistent with it not being exercised. This PR does not modify it and does not add it to any list; flagging it for whoever owns that test.PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
If PR introduces API changes, an appropriate PR label is added - either
api-compatibleorapi-breaking. Forapi-breaking, includeBREAKINGin the PR title.Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
Update tava architecture diagram if there is a significant design change in PR.
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
To see a list of available CI bot commands, please comment
/bot help.