Skip to content

[FEA](DynamicEmb) async erase by score - #532

Merged
shijieliu merged 11 commits into
NVIDIA:mainfrom
jiashuy:feat/dynamicemb-async-erase
Nov 3, 2026
Merged

shijieliu merged 11 commits into
NVIDIA:mainfrom
jiashuy:feat/dynamicemb-async-erase

Conversation

@jiashuy

@jiashuy jiashuy commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Summary

Adds erase_by_score_async(model, score_strategy, threshold, ...) to DynamicEmb: it erases, in the background of training, every key whose score is below a threshold, and returns a handle to wait on. The use it is for is a table that never evicts (NO_EVICTION) and is scored by time or by step: a job drops the keys it has not seen for a while, and the room they free is what the next keys take, so the table stops growing.

The PR is built from eleven commits, in this order:

  1. 7150e94 skip the per-slot ref counter for storages that never pin;
  2. 67862c7 let a NO_EVICTION table reuse what an erase frees;
  3. dc8a6b2 add erase_by_score (kernel and storage scan) and give a reclaimed slot its own digest;
  4. 3162603 add erase_by_score_async (gate, worker, handle, the module and user-level API, docs);
  5. 2718dcf do not read the device for rows a full value buffer cannot grow to;
  6. 752d202 doc: fix(dynamicemb): index reference counters across logical tables #514 fixed the ref counter indexing the erase work found;
  7. a78a860 mark a table erase_untracked when erase_by_score removed keys from it;
  8. 3a55c47, 66bbfd6 and 9ea4b24 stress tests;
  9. 0835c98 the example: --erase_interval and --erase_retention.

What a user gets

  • dynamicemb.erase_by_score_async(model, score_strategy, threshold, stream=None, chunk_slots=..., max_in_flight=...) works on a DistributedModelParallel / module that holds dynamicemb tables, and BatchedDynamicEmbeddingTablesV2.erase_by_score_async(...) on one module. It returns an EraseHandle (done, wait, wait_stream, result() -> (erased, spared)), summed over the modules and tables.
  • Only tables whose score strategy has score_strategy as a member are scanned. HBM-only and CACHING layouts are allowed (the storage behind the cache is erased); host-only, hybrid and parameter-server layouts are refused with NotImplementedError, before anything is erased.
  • Keys a prefetched batch is using are pinned until its backward and are spared; the count of them comes back in spared.
  • erase_by_score marks a table erase_untracked when it removed keys from it, so incremental_dump says so in its meta and replay_increment refuses a delta that cannot be replayed faithfully.
  • example/example.py shows it: with --train or --dump, --erase_interval N asks every N batches for an erase of the keys not seen for --erase_retention (default 1000; batches with --score_strategy step, seconds with timestamp; --erase_interval 0, the default, is off). 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. It is refused with lru_lfu (a (TIMESTAMP, LFU) table cannot be erased by either score), --external_storage and --incremental_dump (an erase by score is not recorded, so the deltas could not be replayed). The README of the example has the commands.
  • DynamicEmb_APIs.md documents the call; docs/async_erase_design.md has the design, the measurements and the limits.

How it works

  • Kernel. erase_by_score scans a range of slots and erases, for a table, the keys below the threshold; a slot keeps its value row when it is reclaimed, and a reclaimed slot has a digest of its own so a lookup cannot mistake it for the key that was in it. A key with a ref counter above zero is spared.
  • One worker per module. Each module has one AsyncEraser (a single-thread executor), so the erases of a module run in the order they were asked for. The scan is cut into chunks (ERASE_CHUNK_SLOTS = 1 << 22 slots by default).
  • A gate between training and the scan. The prefetch of a batch takes the table's TableAccessGate from expand_if_need to the end of find-and-increment; the scan takes it for one chunk at a time and re-reads the key map each time, restarting a table's scan if an expansion replaced the key map (key_map_generation). So training waits for a chunk, not for the whole scan.
  • A fair lock. The gate's lock hands over to its waiters in order. A plain threading.Lock let the scan thread barge in again and again, and a stress test with a hot loop showed a step starved for a long time; this was measured, and is why FairLock exists (design doc, 4.5).
  • A bound on what is in flight. At most max_in_flight (default 2) chunks may be launched and not finished, and the scan waits for the oldest one outside the gate. On a 2^29-slot table on an H100 this kept the training step's time close to that with no erase (design doc, 4.8).
  • A stream. The erase runs on a stream of the module's own by default. A stream given by the caller is used as it is; the current, default and prefetch streams of the module give a UserWarning.

Related fixes in this PR

  • A reclaimed slot's own digest and the reuse of freed rows by a NO_EVICTION table (what lets an erase make room), with the row/key-map sizing (_expand_if_need_no_eviction, _grow_values_only) that goes with it.
  • rows_short in _expand_if_need_no_eviction no longer asks the device again for tables whose value buffer is already as large as it can get: before, every batch read the device once the buffer was full.
  • The per-slot ref counter is skipped for storages that never pin. The multi-table ref counter indexing bug the erase work found was fixed separately in fix(dynamicemb): index reference counters across logical tables #514, and this branch is rebased on it.

Tests

New, in test/unit_tests/erase_async/ (all in test_erase_async.sh, which unit_test.sh runs):

  • test_erase_by_score.py, test_storage_erase_by_score.py: the kernel and the storage's scan in chunks (slots, digests, ref counters, restarts on expansion, the erase_untracked marking, the in-flight bound);
  • test_async_erase.py: the gate, the fair lock, the worker and the handle, alone and on a module beside a prefetch;
  • test_erase_api.py: what a user calls (argument checks, layouts, strategies, streams);
  • test_erase_end_to_end.py: a sliding window of keys keeps the table the same size, training goes on during an erase, the cache case, the same key in two tables;
  • test_erase_distributed.py: the call on a sharded DistributedModelParallel, two ranks, torchrun;
  • test_erase_stress.py: one rank, a DistributedModelParallel around an EmbeddingCollection, batches of ~64k keys, tables that grow past a million keys, an erase_by_score_async every 10 steps that nothing waits for; at the end the tables are compared with a host model of the step that last trained each key (present iff trained at or after the last threshold). The tables are constant-initialised and the learning rate is 0, so every key must read that constant.

Also: two tests in incremental_dump/test_replay_increment.py (an erase by score makes the delta unreplayable; one that removes nothing leaves it replayable), table_operation/test_table_operation.py, test_table_rows.py, test_no_eviction_row_indexing.py.

Verification

GPU runs on EOS (H100):

  • unit_test.sh fwd_bwd: exit 0 at 3a55c47 (and at 59f4c13 before it). unit_test.sh load_dump: exit 0 at 59f4c13 and at 3a55c47 (6224 s, no FAILED/ERROR/Traceback in the log).
  • test_erase_stress.py as it is in 9ea4b24 (single rank, torchrun --nproc_per_node 1): three runs at the default size and one at twice the batch and 200 steps, all passed. The tables are built with bucket_capacity=128 so that they grow and a scan is cut into chunks, and the test fails if they never grow: 1 to 2 expansions seen at the default size (3 to 4 at twice), 829,937 keys left per table at the default size.
  • example.py on two ranks (MovieLens): --train without the new flags as before; --train with --erase_interval 50 --erase_retention 100 (step), with --score_strategy timestamp --erase_retention 1, and with --caching --prefetch_pipeline; --dump with an erase, then --load: all exit 0, 185 to 306 keys erased per epoch per rank by step (about 3300 to 3500 by a one-second timestamp retention), none spared, and a loss that falls as without the erase. The four refused combinations exit 1 with the parser's message.
  • Before it, the module-level version of this test (in 3a55c47) passed three runs at the default size and one at twice, with erase_async/ 146 passed (and the two-rank torchrun case), incremental_dump/test_replay_increment.py 35 passed, table_operation/ 895 passed.

Known limits

  • An erase asked for while the table is being filled races with the training by design: a key below the threshold that a step re-reads is either spared or erased and put back by the step; either way it is there.
  • No retention: erase_by_score_async retains nothing, so a table it removed keys from is erase_untracked and its incremental dumps cannot be replayed.
  • The time a chunk holds the gate is the scan of chunk_slots slots; it can be cut with chunk_slots, at the price of more launches.
  • See docs/async_erase_design.md, sections 8 and 9, for the gaps in the tests and the limits.

Checklist

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

@jiashuy jiashuy changed the title Feat/dynamicemb async erase [FEA](DynamicEmb) async erase by score Nov 2, 2026
@jiashuy
jiashuy force-pushed the feat/dynamicemb-async-erase branch from 165e811 to 1891618 Compare November 2, 2026 07:45
@greptile-apps

greptile-apps Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The latest changes appear safe to merge; no new blocking issue was found.

Summary

Adds background removal of DynamicEmb keys below a score threshold.

  • DynamicEmb erases low-scoring keys in chunks while training continues.
  • NO_EVICTION tables reuse erased slots instead of growing for every new key.
  • Incremental replay now refuses deltas after unrecorded erases remove keys.
  • Storages that never pin keys no longer allocate per-slot reference counters.

The latest changes add the example usage. No new actionable issues were found. Previous threads were unnumbered, so they have no entries in previousFindings.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
    A[Training batch] --> B[Prefetch takes table gate]
    B --> C[Find and pin keys]
    C --> D[Forward and backward]
    D --> E[Release pins]
    F[Erase request] --> G[Background worker]
    G --> H[Take gate for one chunk]
    H --> I[Remove old unpinned keys]
    I --> J{More chunks?}
    J -->|Yes| H
    J -->|No| K[Finish handle]
    K --> L[Wait before evaluation or dump]
Loading

Reviews (8) · Last reviewed commit: "[FEA](DynamicEmb) Add --erase_interval a..." · Reviewed by Greptile

@jiashuy
jiashuy force-pushed the feat/dynamicemb-async-erase branch from 1891618 to 59f4c13 Compare November 2, 2026 09:19
@jiashuy

jiashuy commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator Author

Unit test passed

@jiashuy
jiashuy force-pushed the feat/dynamicemb-async-erase branch from b9aba58 to fe23490 Compare November 3, 2026 01:36
jiashuy and others added 7 commits November 3, 2026 08:56
…er 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]>
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]>
…wn 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]>
…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]>
… 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]>
…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]>
…ase_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]>
@jiashuy
jiashuy force-pushed the feat/dynamicemb-async-erase branch from fe23490 to a78a860 Compare November 3, 2026 03:27
jiashuy and others added 2 commits November 3, 2026 11:02
…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]>
…ngCollection

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]>
jiashuy and others added 2 commits November 3, 2026 12:08
…ks, 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]>
…xample

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]>
@shijieliu
shijieliu merged commit 2d1dfcb into NVIDIA:main Nov 3, 2026
1 check passed
tiankongdeguiji added a commit to tiankongdeguiji/recsys-examples that referenced this pull request Nov 3, 2026
…yout

Conflicts (both sides added a keyword argument at the same spot) resolved by
keeping both: `global_capacities` / `global_bucket_layout` from this branch
beside `use_ref_counter` from NVIDIA#532 in create_table_state, get_scored_table,
LinearBucketTable.__init__, _expand_tables_impl and the HybridStorage tiers;
the `table_insert*_single_score` helpers take NVIDIA#532's optional counter and
this branch's global capacity pointer.

Rebuilt and re-ran on the merged tree: test_global_bucket_layout (31),
kuairand (17), replay (36), planner, no_eviction (24), table_rows, expansion,
ref counters, table_operation, the erase_async suite (143) incl. the
distributed case, and multi-GPU hash_bucket / hash_roundrobin / roundrobin
dump-load.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01JoQS7n2bkEWZws9Rddef49
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