Skip to content

fix(dynamicemb): wait for queued GPU work before freeing VMMTensor memory - #526

Merged
shijieliu merged 4 commits into
NVIDIA:mainfrom
shijieliu:fix/vmm-free-sync-20261026
Nov 9, 2026
Merged

shijieliu merged 4 commits into
NVIDIA:mainfrom
shijieliu:fix/vmm-free-sync-20261026

Conversation

@shijieliu

Copy link
Copy Markdown
Collaborator

Description

When the last reference to a DynamicEmb device buffer (VMMTensor) goes away while GPU work that uses it is still queued, the queued kernels read or write unmapped memory. They fail with "CUDA error: an illegal memory access was encountered". The error is sticky, so it shows up later, at an unrelated CUDA call. A typical case is a model dropped right after its last training step, with no device sync.

~VMMTensor() calls cuMemUnmap, cuMemRelease and cuMemAddressFree at once. Unlike cudaFree, these do not wait for the GPU, and the tensors from data() do not own the memory. Host buffers are safe: the cudaHostUnregister in ~HostVMMTensor() waits for the queued work. The CUDA docs do not promise this, so the new test checks it.

Fix: ~VMMTensor() first waits for all work queued on the buffer's device (cuCtxSynchronize on its primary context), as cudaFree does. The wait covers every stream. It never throws, never creates a context, and keeps the caller's current context and device. If the wait fails, for example after a sticky error, the memory is still freed. Because the wait is a device sync, it has two limits:

  • It also waits for queued NCCL kernels. If a peer launches its side of a queued collective only after a host-side step (such as a gloo barrier) that this rank reaches after the drop, the ranks deadlock. Finish pending collectives before dropping a table. Host buffers on main hang the same way.
  • It is not allowed during CUDA graph capture, so dropping a device buffer during a capture breaks that capture. cudaFree breaks global and thread_local captures the same way.

Tests:

  • New test_vmm_tensor.py::test_drop_waits_for_queued_gpu_work. It queues a fill and a copy behind a long GPU sleep, drops the buffer, and then syncs. It covers device and host buffers, with the work on the current stream, on a side stream, or on a second GPU. Each case runs in a child process, because the error is sticky.
  • On main (d0dbc08), the three device cases fail in 10 of 10 runs with "CUDA error: an illegal memory access was encountered" at the sync after the drop. The three host cases pass. The full test_vmm_tensor.py gives 32 passed, 3 failed.
  • With this PR, all six cases pass in 10 of 10 runs (4 passed, 2 skipped on one GPU). test_vmm_tensor.py: 35 passed. test_batched_dynamic_embedding_tables_v2.py: 390 passed, 4 skipped. test_expansion_value_capacity.py: 11 passed. test_no_eviction_row_indexing.py: 10 passed. test_sequence_embedding.sh: exits 0, with 3028 iteration checks passed.
  • All runs: one node with 8 H100 GPUs, 26.07 CI image (CUDA 13.3, PyTorch 2.13, TorchRec 1.8).

Checklist

  • I am familiar with the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

🤖 Generated with Claude Code

shijieliu and others added 2 commits October 29, 2026 09:49
Add test_drop_waits_for_queued_gpu_work to test_vmm_tensor.py. It queues
a fill of a buffer and a copy out of it behind a long GPU-side sleep,
drops the last reference to the buffer before they run, and then
synchronizes. The memory must stay mapped until the queued work is done,
and the copy must hold what the fill wrote. The cases cover device
(VMMTensor) and host (HostVMMTensor) buffers, with the work on the
current stream, on a side stream, or on GPU 1 while GPU 0 is current at
the drop. The last case needs 2 GPUs (it is skipped otherwise), and it
also checks that the drop leaves GPU 0 current.

An illegal memory access is sticky and breaks the CUDA context for the
rest of the process. So each case runs in a child process (the test
file itself), and the test checks the child's exit status and output.
The child gets the test's sys.path as PYTHONPATH, so it imports the same
dynamicemb build as the test, also when pytest runs from an in-place
build with no PYTHONPATH set.

On this commit the three device cases fail in 10 of 10 runs, with "CUDA
error: an illegal memory access was encountered" at the synchronize
after the drop (2 H100 GPUs; CUDA 13.3, PyTorch 2.13 from the 26.07
image). ~VMMTensor() unmaps and releases the memory at once, and the
queued fill then writes to unmapped memory. The host cases pass:
cudaHostUnregister, which ~HostVMMTensor() calls, waits for the queued
work (the drop blocks for the 0.5 s of the GPU sleep), so they guard
that path. The full test_vmm_tensor.py gives 32 passed and 3 failed
(the three device cases).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…mory

~VMMTensor() calls cuMemUnmap, cuMemRelease and cuMemAddressFree at
once. Unlike cudaFree, these do not wait for the GPU. The tensors from
data() do not own the memory, so when the last reference to a table's
buffer goes away, kernels still queued in a stream read or write
unmapped memory. They fail with "an illegal memory access", and the
error is sticky, so it shows up at a later, unrelated CUDA call. A
typical case is a model dropped right after its last training step,
with no device sync.

Wait for all work queued on the buffer's device before freeing, as
cudaFree does. PyTorch also waits for queued work before it unmaps an
expandable segment. The wait is a device sync (cuCtxSynchronize on the
device's primary context), so it covers every stream: DynamicEmb
kernels run on whichever stream is current, and TorchRec pipelines use
several. It never throws: if the sync fails, for example after a sticky
error, the memory is still freed. It never creates a context, and it
keeps the caller's current context and device unchanged.

The other paths need no wait. ~HostVMMTensor() and
HostVMMTensor::extend() call cudaHostUnregister, which waits for the
queued work by itself (in both, the call blocks until a queued 0.5 s
GPU sleep ends, and the data are intact). The CUDA docs do not promise
this, so the comment in ~HostVMMTensor() calls it measured driver
behavior, and the host cases of the new test check it.
HostExtendableBuffer.extend() also synchronizes before it grows the
buffer. VMMTensor::extend() only maps new pages after the old ones. The
error paths of both constructors and extend() release only memory that
no kernel has used yet.

Cost and limits: tables extend their buffers and never replace them,
so this is one device sync per table when a model is dropped, and it
returns at once when the GPU is idle. The sync waits for every kernel
queued on the device, on any stream, NCCL kernels included, and a
collective finishes only when the peers launch their side. So a drop
deadlocks if a peer launches its side of a queued collective only after
a host-side step (a gloo collective, a barrier, a store wait) that this
rank reaches after the drop. A 2-rank probe shows it: rank 0 queues an
all_reduce, drops a device buffer, and then meets rank 1 at a gloo
barrier, after which rank 1 launches its all_reduce. Without the wait,
both ranks finish at once; with it, rank 0 stays in the drop until
rank 1's barrier times out after 20 s. Host buffers hang the same way
without this change: with a host buffer, the probe also hangs on the
parent commit, because cudaHostUnregister waits for the queued
all_reduce. In such flows, finish pending collectives before dropping a
table.

A device sync is also not allowed during CUDA graph capture. So
dropping a device buffer while a graph is being captured breaks that
capture, in the global, thread_local and relaxed modes; the memory is
still freed. cudaFree, and the cudaHostUnregister in ~HostVMMTensor(),
break global and thread_local captures the same way, while relaxed mode
allows them.

Tests (one H100 node on Eos; CUDA 13.3, PyTorch 2.13 nv26.07, TorchRec
1.8). "Before" is the parent commit, which adds only the test:
- test_vmm_tensor.py::test_drop_waits_for_queued_gpu_work with 2 GPUs:
  before, the three device cases fail with an illegal memory access in
  10 of 10 runs, and the three host cases pass; after, all six cases
  pass in 10 of 10 runs. With 1 GPU, after: 4 passed, 2 skipped.
- The same test from the in-place build with no PYTHONPATH (python -m
  pytest in corelib/dynamicemb): before, 3 failed (illegal memory
  access) and 3 passed; after, 6 passed.
- test_vmm_tensor.py with 2 GPUs: 32 passed and 3 failed (the three
  device cases) before; 35 passed after.
- test_batched_dynamic_embedding_tables_v2.py: 390 passed, 4 skipped,
  before and after.
- test_expansion_value_capacity.py (11 passed) and
  test_no_eviction_row_indexing.py (10 passed), before and after.
- test_sequence_embedding.sh (11 torchrun runs on 2, 4 and 8 GPUs, 7 on
  one GPU): exits 0 with 3028 passed iteration checks, no traceback
  and no illegal memory access, before and after.
- After a sticky illegal memory access, dropping a device and a host
  buffer does not throw, and the process exits with status 0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@greptile-apps

greptile-apps Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge within its documented limits.

Summary

Adds a wait before freeing device and host buffers so queued GPU work can finish.

  • Device and host buffers wait for queued GPU work before freeing memory.

shijieliu explicitly documents two accepted limits: pending collectives can deadlock when peers need a later host-side step, and dropping a buffer during CUDA graph capture breaks that capture.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Last buffer reference dropped] --> B[Find active primary context]
    B --> C{Context active?}
    C -->|Yes| D[Push buffer context]
    D --> E[Wait for queued GPU work]
    E --> F[Restore caller context]
    C -->|No| G[Free buffer memory]
    F --> G
Loading

Reviews (3) · Last reviewed commit: "Merge branch 'main' into fix/vmm-free-sy..." · Reviewed by Greptile

jiashuy and others added 2 commits November 9, 2026 15:20
~HostVMMTensor relied on cudaHostUnregister to wait for queued GPU work,
which the CUDA docs do not promise. Call wait_for_device_work() before
unregistering, as ~VMMTensor does. wait_for_device_work() now logs the
step that failed instead of ignoring it; the memory is still freed.

The regression test sizes its GPU delay from the device clock rate
instead of assuming 2 GHz.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@shijieliu
shijieliu merged commit d03198c into NVIDIA:main Nov 9, 2026
shijieliu added a commit to shijieliu/recsys-examples that referenced this pull request Nov 9, 2026
Merge main up to d03198c (NVIDIA#536, NVIDIA#534, NVIDIA#529, NVIDIA#527, NVIDIA#526).

- NVIDIA#527 sends empty weights for an empty input under index dedup, the
  change this branch made in shard/embedding.py: the merge keeps main's
  docstring and comments and this branch's needs_counters, the same
  condition.
- NVIDIA#529 adds PrefetchState.key_map_generation and _slots_after_rehash,
  and looks a prefetched batch's slots up again in its backward when a
  later prefetch rehashed the table. Git put _slots_after_rehash between
  PrefetchState's fields and this branch's record_stream, which then fell
  out of the class without a conflict; the merge puts it back. The
  lookup's row map (out_rows, grad_rows) only says where rows go, and the
  forward's load_from_flat_by reads value rows, which a storage keeps
  through a rehash.
- NVIDIA#534 (each table's HBM budget in fused groups), NVIDIA#536 (erase_by_score
  for lru_lfu tables, per named table) and NVIDIA#526 (VMMTensor frees after
  the queued work) merge without conflicts.

Every file of test/unit_test.sh passes on one node, each group's .sh
files with its DYNAMICEMB_TEST_GROUP, and so does the HSTU end-to-end
test on one node and on 2. On 2 nodes test_hier_dist.py (122),
test_hier_overflow.py (79) and test_hier_pipeline.py (45) pass, and on 4
nodes test_hier_dist.py (122).

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants