Skip to content

fix(dynamicemb): index reference counters across logical tables - #514

Merged
shijieliu merged 2 commits into
NVIDIA:mainfrom
lidongdongbuaa:bug-multitable-refcounter
Nov 3, 2026
Merged

shijieliu merged 2 commits into
NVIDIA:mainfrom
lidongdongbuaa:bug-multitable-refcounter

Conversation

@lidongdongbuaa

@lidongdongbuaa lidongdongbuaa commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

When several logical tables share a reference-counter buffer, insertion into a later table reads the first table's counters during eviction. For example, table 1's local slot 7 is counter 135 with a 128-slot table 0, but the old eviction path reads counter 7. This can evict an in-use key or incorrectly return Busy because another table has references.

Use the global bucket offset in both insert_body and insert_and_evict_body. Returned slot indices stay table-relative. The overflow counter pointer is already shifted per table and is unchanged.

Add 64 parameterized regression cases covering 128/1024-slot buckets, int64/uint64 keys, ASSIGN/LRU_LFU policies, insert/collect/evict/overflow paths, and either table holding references. They check victim identity, protected-key retention, counter placement/release, output indices, and that table 0 is unchanged when inserting into table 1.

Historical GPU validation of the original fix (4a0449a), on one NVIDIA H100 80GB, Torch 2.11.0, CUDA 13.2, TorchRec 1.5.0:

Check Result
Full native extension builds and imports, original and fixed kernels Passed
New regression with the original kernel 64/64 fail on the intended assertions; no errors or skips
New regression with the fixed kernel 64/64 pass
Fixed regression plus existing table-operation and LRU/LFU tests, with numba-cuda installed 667/667 pass; no errors or skips
compute-sanitizer memcheck on the 64 new cases 64 pass, 0 memory errors
isort, autoflake, codespell, Black and mypy hooks Passed

The GPU run used a downstream checkout. At validation time, the table-operation sources, scored-table Python API, JIT code, these test modules and setup.py were verified byte-for-byte identical to commit 4a0449a. Subsequent merges of main changed these sources; the historical results do not validate the current merged head. This is targeted GPU validation, not a claim that the entire upstream repository CI has passed.

Review follow-up (2026-11-02): register test_multitable_ref_counter.py in test/unit_tests/table_operation/test_table_operation.sh, so both the direct table-operation runner and bash test/unit_test.sh fwd_bwd invoke the 64-case regression. On macOS, bash -n and git diff --check pass; command shims verified both actual shell entry points invoke the regression exactly once, preserve the one-/eight-rank dump/load invocations, and immediately propagate an injected regression failure (exit 37). These are runner checks; pytest/CUDA execution was stubbed and the current merged head has not been rerun on a GPU.

From corelib/dynamicemb, build with DEMB_ARCHS=90 TORCH_CUDA_ARCH_LIST=9.0 MAX_JOBS=4 python setup.py build_ext --inplace, then run:

python -m pytest -q \
  test/unit_tests/table_operation/test_multitable_ref_counter.py \
  test/unit_tests/table_operation/test_table_operation.py \
  test/unit_tests/table_operation/test_lru_lfu.py
compute-sanitizer --tool memcheck --error-exitcode 99 \
  python -m pytest -q test/unit_tests/table_operation/test_multitable_ref_counter.py

An independent harness invoking the production CUDA insertion kernel also reproduces both failure directions: protecting table 1 changes 64 incorrect evictions to 64 Busy results; protecting only table 0 changes 64 incorrect Busy results to 64 normal evictions. No general throughput improvement is claimed: the synthetic unprotected 1024-slot same-bucket case measured 3.547712 ms before and 3.803712 ms after, with a similar shift in the table-0 control.

DCO sign-off added to both PR commits on 2026-11-02 with the contributor's explicit authorization: Signed-off-by: lidongdong.2024 <[email protected]>. The branch was rebased to remove merge-only commits; the final Git tree is identical to the pre-sign-off head e4b7813.

Change type: bugfix. A maintainer needs to apply the bugfix label; this fork author does not have label permissions.

@lidongdongbuaa
lidongdongbuaa marked this pull request as ready for review October 30, 2026 06:50
@greptile-apps

greptile-apps Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable new issues remain.

Summary

The PR fixes reference-counter reads across logical tables while keeping returned slot indices table-relative.

  • Eviction checks reference counters in the right logical table.

The head descends from the previous review commit, both share the same target merge base, and their trees are identical. No new code changes or rule violations were found. Current-head GPU tests were not run during this review.

Reviews (4) · Last reviewed commit: "test(dynamicemb): register multitable re..." · Reviewed by Greptile

@lidongdongbuaa
lidongdongbuaa force-pushed the bug-multitable-refcounter branch from e4b7813 to 7e37ff4 Compare November 2, 2026 04:47
@lidongdongbuaa
lidongdongbuaa force-pushed the bug-multitable-refcounter branch from 7e37ff4 to 21155d9 Compare November 2, 2026 05:41
@shijieliu
shijieliu merged commit 0f5c0a0 into NVIDIA:main Nov 3, 2026
1 check passed
jiashuy added a commit to jiashuy/recsys-examples that referenced this pull request Nov 3, 2026
…the erase work found

While checking how the ref counter is indexed for the erase kernel, the evict
kernels turned out to read it with a table-relative offset, so a pinned slot of
the second table onwards was evicted as if it were free. NVIDIA#514 fixed it upstream
and this branch is rebased onto it. The design document recorded it as not
fixed; it now says where it was fixed and what tests it left.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@jiashuy jiashuy mentioned this pull request Nov 3, 2026
3 tasks done
shijieliu pushed a commit that referenced this pull request Nov 3, 2026
* [FEA](DynamicEmb) Skip the per-slot ref counter for storages that never pin

Only a cache and an HBM-direct DynamicEmbStorage pin slots (a prefetched
batch holds them until backward). The storage under a cache, a host-value
storage and both HybridStorage tiers took the generic or cache path, never
incremented the counter, and still paid 4 bytes per slot of GPU memory, which
is a lot for a large table.

Add use_ref_counter (default True) to LinearBucketTable, get_scored_table,
create_table_state and DynamicEmbStorage. When False, _ref_counter is None,
increment_counter / decrement_counter raise, and the evict kernels skip their
counter check on a null pointer (reduce, reduce_ranked, the lock-then-recheck
in insert). The insert / insert_and_evict bindings take the counter as an
optional tensor; the overflow path still requires it. Expansion keeps the
flag. A storage under a cache, a host-only storage and HybridStorage now pass
False.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [FEA](DynamicEmb) Let a NO_EVICTION table reuse what an erase frees

A table that never evicts was sized by the rows it had handed out, and a slot
keeps its row after an erase, so erasing keys freed nothing: new keys took
never-used slots and fresh rows, and the key map and value buffer kept
doubling while the live set stayed the same size.

Size the two by what each has to hold. The key map grows when the keys it
holds (plus the batch) pass the 0.5 load factor. The value buffer grows when
the rows handed out (plus the batch) pass its rows, at least doubling and never
past the key map's slots, since a slot owns one row. A table whose keys keep
being replaced then settles at one row per slot. _expand_tables_impl leaves the
value buffer of such a table to _grow_values_only; every other strategy is
unchanged.

With the buffer as large as the key map, a full bucket is made of keys in use
and erased slots and has to give up an erased one. NO_EVICTION alone kept its
one score word at 0 for every key, so a key in use tied with an erased slot and
could be the one given up (about 40% of a 1500-key live set lost per round in a
half-replacing workload). Add a FLAG score policy: a key sets its word to 1, an
erase clears it to 0, reads leave it alone. NO_EVICTION alone uses it for
inserts and loads; CONST keeps its meaning (no score change) for finds and for
re-inserting existing keys. A table that keeps the user's score
((NO_EVICTION, CUSTOMIZED) and PRECISE_CUSTOMIZED) must not be given a score of
0, which would tie the same way; the API docs say so.

Tests drive training for real (forward and backward, learning rate 0): a
forward-only loop leaves the reference counters pinned and the eviction search
skips pinned slots, which hid all of this.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [FEA](DynamicEmb) Add erase_by_score, and give a reclaimed slot its own digest

erase_by_score erases the keys of a range of slots whose score is below a
threshold. It is the scan an async erase will be built on: the kernel reads only
the key and score of each slot, never a value or a row, locks a slot with the same
compare-and-swap as an insert or a score-updating lookup, reads the score again
under the lock (a lookup may have just used the key), and spares a slot whose ref
counter is above zero. It adds [erased, spared] to a device tensor and waits for
nothing, so a caller scans a big table in chunks and reads the counts once. The
binding releases the GIL and checks every tensor it indexes (counts contiguous and
on the table's device, bucket_sizes one int32 per bucket, counter one int32 per
slot), since a wrong one is an out-of-bounds write found much later. The grid
stride is 64-bit. LinearBucketTable.erase_by_score wraps it with a table-relative
range, for a single-score table without an overflow area.

A slot an erase leaves reclaimed holds ReclaimKey, but was given the digest of an
empty slot, so every probe looking for a free slot took it for a candidate and
read its key, more of them the more keys had been erased. Add
Bucket::reclaimed_digest() (the digest of ReclaimKey, as a slot carries the digest
of the key it holds) and write it everywhere a slot ends reclaimed: the key-by-key
erase, erase_by_score, the placement of carried rows in a rehash (which wrote no
digest at all), and the restore of reclaimed slots on a replay, in both the case
of an empty slot and of a live key. The digest is not stored in a checkpoint.

Tests live in a new test/unit_tests/erase_async/, with a launcher registered in
unit_test.sh: erase_by_score on a table (strictly below, thresholds 0 and huge, no
counter, chunks, two tables, a pinned slot of either table, reinsertion, argument
and tensor checks, the digest left behind), plus digest checks beside the rehash,
restore and key-by-key erase tests in test_table_rows.py.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [FEA](DynamicEmb) Add erase_by_score_async: erase keys below a score beside training

Erase, in the background of training, the keys whose score is below a
threshold. Built on the erase_by_score kernel of 4ec7d48.

API
- erase_by_score_async(model, score_strategy, threshold, stream=None,
  chunk_slots=2**22, max_in_flight=2) -> EraseHandle, and the same call as a
  method of BatchedDynamicEmbeddingTablesV2. It finds the tables the way
  DynamicEmbDump does, picks those whose score strategy has the one named as a
  member ((NO_EVICTION, PRECISE_CUSTOMIZED) is picked by PRECISE_CUSTOMIZED),
  and returns at once. HBM-only and cache layouts are supported; host-only,
  HybridStorage and external-storage layouts are refused. Every argument is
  checked before anything starts.
- EraseHandle: done(), wait(), wait_stream(stream), result() -> (erased,
  spared). A model with several modules gets an EraseHandleGroup.
- The stream is optional: by default a module makes one of its own, so the scan
  overlaps the training; the stream the training uses is accepted with a
  warning.

Concurrency
- One worker thread per module launches the scan; prefetch and the scan meet
  in a TableAccessGate (a lock, plus a CUDA event handed from one holder to the
  next so the kernels are ordered on the device). Prefetch takes it from
  expand_if_need through the find and the counter increment; the scan takes it
  once per chunk and re-reads the key map each time, and starts a table again
  from its first bucket if an expansion replaced it (key_map_generation).
- The gate's lock is a FairLock: with threading.Lock the worker, letting go and
  asking again at once, kept the training thread out for a whole scan, which
  made the stress test depend on the scheduler.
- At most max_in_flight chunks are launched and unfinished at once, so what
  the next prefetch waits for on the device is bounded.
- The default chunk (2**22 slots) and limit (2) were measured on an H100: a
  table of 2**29 slots, training steps of 0.7 ms and scans back to back slow a
  step by about 10%, against 110% for chunks of 2**24 and 6x with no limit on
  chunks in flight. The scans measured only read; the cost while erasing was not
  measured (docs/async_erase_design.md, 4.8).

Tests: test/unit_tests/erase_async/ (143 pytest items, and a torchrun script
on a DistributedModelParallel of two ranks): the kernel, the chunked scan, the
lock, the gate, the worker and the handle, the API, and end-to-end cases
(a sliding window on a table that never evicts, a cache, two tables, pinned
keys). docs/async_erase_design.md lists what they do not cover.

Docs: DynamicEmb_APIs.md, docs/async_erase_design.md.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [FIX](DynamicEmb) Do not read the device for rows a full value buffer cannot grow to

A table that never evicts settles at one value row per key-map slot when its
keys churn (a sliding window with erases). From then on the rows handed out
equal the rows of the buffer, so rows + this batch's unique keys is always
above it and rows_short was true for every batch: each prefetch copied the
table sizes and the row counts to the host and waited for the device twice,
only for _grow_values_only to find nothing to grow, since a buffer never
passes the key map's slots.

rows_short now ignores a table whose buffer already covers every slot of its
key map. The growth of the key map itself is still checked apart, by
get_expand_info, and once the key map grows the buffer is short of slots again.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [DOC](DynamicEmb) Say that #514 fixed the ref counter indexing the erase work found

While checking how the ref counter is indexed for the erase kernel, the evict
kernels turned out to read it with a table-relative offset, so a pinned slot of
the second table onwards was evicted as if it were free. #514 fixed it upstream
and this branch is rebased onto it. The design document recorded it as not
fixed; it now says where it was fixed and what tests it left.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [FIX](DynamicEmb) Mark a table erase_by_score removed keys from as erase_untracked

erase_by_score removes keys without recording them, and a storage keeps a value
row per key, so each erased slot is left reclaimed with its row. An unretained
erase_keys marks its table (erase_untracked) so that the incremental dump says
its delta cannot be replayed exactly and replay_increment refuses it. The scan
did not: the delta of a TIMESTAMP or CUSTOMIZED table looked complete, and a
replica was left with the keys the source had erased, and their rows.

Each table is now scanned into a count of its own, read back when the table is
done (the worker waits for its own stream only) and added to the caller's
counts. A table from which any key was removed is marked, also when the scan
fails half way; one the call found nothing to remove in is not, since the mark is
sticky. replay_increment's message names erase_by_score_async as well.

Tests: the storage marks only the table that lost keys; the delta of a source
that erased by score is refused by replay_increment, and one after a call that
removed nothing is replayed. Docs: DynamicEmb_APIs.md, the field description of
incremental_dump, and the design document.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [TEST](DynamicEmb) Stress erase_by_score_async in a training loop at a realistic size

Train batches of ~64k keys on a table that grows past a million keys, ask for an
async erase every 10 steps without waiting, and compare the table at the end with
a host model of the step that last trained each key. One and two tables.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [TEST](DynamicEmb) Run the erase stress loop on a DMP-wrapped EmbeddingCollection

Replace the module-level stress test with one on a DistributedModelParallel around an
EmbeddingCollection, on one rank (torchrun), so the keys take the path a user's do and
the erase is the erase_by_score_async(model, ...) a user calls. Same workload and host
model; the value check is that every key reads the constant initial value (learning rate 0).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [FIX](DynamicEmb) Let the DMP stress test's tables grow, scan in chunks, and keep a learning rate of 0

create_model uses MAX_BUCKET_CAPACITY, which on one rank makes one bucket of the whole table:
the table could not grow and a scan could not be cut into chunks. Set bucket_capacity=128
next to init_capacity, and assert that the tables did grow, so the restart is tried.

The fused parameter is "learning_rate"; "lr" is not read and left the default 0.01, which
trained every key a step and failed the check that each key reads its constant initial value.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* [FEA](DynamicEmb) Add --erase_interval and --erase_retention to the example

Every --erase_interval batches of --train or --dump, ask for an erase_by_score_async of the
keys not seen for --erase_retention (batches for the step score, seconds for timestamp). The
threshold is read from the tables' own score with get_score; each epoch ends by waiting for
the erase in flight and prints what this rank erased. Refused with lru_lfu, --external_storage
and --incremental_dump. The README says how to use it.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
shijieliu added a commit to shijieliu/recsys-examples that referenced this pull request Nov 8, 2026
Merge main up to c6e2bb2 (NVIDIA#514, NVIDIA#530, NVIDIA#532, NVIDIA#498 and three HSTU
inference commits). Main's per-key scores and per-sharding frequency
counters meet the hierarchical dist in the sharding's Python:

- Per-key scores (PRECISE_CUSTOMIZED) travel beside the keys in their own
  tensor; the hierarchical dist does not carry them. A row-wise
  EmbeddingCollection whose tables take a score per key raises under
  output_dist="fused" when it is sharded, and takes TorchRec's dists with
  the usual warning under "auto".
- Frequency counters are decided per sharding. The hierarchical path reads
  its sharding's entry and gives the op weights exactly when
  _dedup_indices attaches them.
- A rank with no keys for a sharding that counts frequencies sends an
  empty weights tensor, so every rank sends the same tensors (on main the
  ranks' all2alls could differ there).
- GroupedEmbeddingsLookup keeps one prefetch, which passes index dedup's
  frequency counters and now main's scores; LFU scores and admission
  counts under a prefetch pipeline then match the plain loop on TorchRec's
  dists too. BatchedDynamicEmbedding.prefetch, which nothing calls, goes.
  PrefetchState.record_stream also records the unique scores.
- unique_op.cu: main's reduce and the shared chain insert merge cleanly.

test_hier_dist.py checks the per-key-score rule under "fused" and "auto",
and LFU with no keys on the last rank. The tests of both sides pass on 1
and 2 nodes.

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