Skip to content

Feat/dynamicemb retain evicted keys - #443

Merged
shijieliu merged 10 commits into
NVIDIA:mainfrom
jiashuy:feat/dynamicemb-retain-evicted-keys
Aug 10, 2026
Merged

shijieliu merged 10 commits into
NVIDIA:mainfrom
jiashuy:feat/dynamicemb-retain-evicted-keys

Conversation

@jiashuy

@jiashuy jiashuy commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Checklist

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

@greptile-apps

greptile-apps Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds two related features to the DynamicEmb library: (1) a retain-evicted-keys mechanism that captures every key evicted from the last-tier embedding storage so it can be retrieved via pop_evicted_keys, and (2) a slot_index field in the refactored DeltaDumpResult that encodes each dumped key's physical storage slot (plus tier bit for HybridStorage) to enable precise replay of incremental dumps.

  • EvictedItemMode.RETAIN_KEY is threaded from DynamicEmbTableOptions through DynamicEmbTableState into a new CUDA kernel path (table_insert_collect_evicted, CollectEvicted=true template specialization, and a matching dyn_emb_insert_collect_entry JIT entry for LruLfu tables). Evicted (key, table_id) pairs are accumulated in per-state GPU chunk lists and drained on pop_evicted_keys or inside incremental_dump.
  • incremental_dump's return type changes from Union[Tuple[Dict, Dict], None] to Dict[str, DeltaDumpResult], consolidating per-table keys, values, evicted keys, slot indices, and metadata into a single structured object. The underlying storage incremental_dump methods are extended to return a third element (slot_index) and now raise NotImplementedError for dist_type='continuous' tables — a regression for any caller that previously used incremental dump on that distribution type.

Confidence Score: 3/5

  • The new retain-evicted-keys path and the CUDA kernel additions look correct, but the unconditional NotImplementedError added to both DynamicEmbStorage and HybridStorage breaks any existing caller of incremental_dump that uses tables with dist_type='continuous', which rw_sharding.py can produce automatically.
  • Two independent locations in key_value_table.py now raise NotImplementedError for dist_type='continuous' tables when incremental_dump is called. This is a runtime regression on a previously-working code path that the planner can set without explicit user action. Returning None for slot_index in that case would preserve backward compatibility without exposing a meaningless value.
  • corelib/dynamicemb/dynamicemb/key_value_table.py (lines 2148–2151 and 2608–2611) — both NotImplementedError guards for dist_type='continuous'.

Important Files Changed

Filename Overview
corelib/dynamicemb/dynamicemb/key_value_table.py Major additions: DynamicEmbTableState gets evicted-key chunk lists, _append_evicted/_pop_state_evicted_keys helper functions, _encode_slot_index for slot/tier packing, and _all_gather_dumped_keys_values is extended to also gather slot_index. Both DynamicEmbStorage and HybridStorage get pop_evicted_keys and their incremental_dump now returns a three-tuple. An unconditional NotImplementedError for dist_type='continuous' tables breaks existing callers of incremental_dump in both storage classes.
corelib/dynamicemb/dynamicemb/incremental_dump.py Introduces DeltaDumpResult dataclass and refactors incremental_dump to return Dict[str, DeltaDumpResult] instead of the old (Dict, Dict) tuple. Adds pop_evicted_keys function with optional pg-based all_gather. The per-table, per-call _all_gather_evicted_keys pattern adds 2 sequential NCCL collectives per retain-enabled table on top of the existing 3 for key/value/slot_index, but is otherwise correct.
corelib/dynamicemb/dynamicemb/batched_dynamicemb_tables.py Adds _shard_world_size capture at construction, pop_evicted_keys method, and refactors incremental_dump to return DeltaDumpResult. The silent fallback when pop_evicted_keys is absent on a storage backend (P2) could hide mis-configuration.
corelib/dynamicemb/dynamicemb/dynamicemb_config.py Adds EvictedItemMode enum (DISCARD/RETAIN_KEY) and corresponding evicted_item_mode field to DynamicEmbTableOptions. Also adds evicted_item_mode to the grouped_key so tables differing in retain mode are not co-located on shared storage.
corelib/dynamicemb/src/table_operation/insert.cu Adds launch_table_insert_collect_kernel (mirroring launch_table_insert_kernel with collect variant) and table_insert_collect_evicted API function. Lock/unlock protocol is correctly preserved for both LruLfu (driver-API cubin) and non-LruLfu (PTX kernel) paths.
corelib/dynamicemb/src/table_operation/kernels.cuh Extends insert_body with CollectEvicted template boolean and adds table_insert_collect_kernel. The warp-ballot compaction for CompactTileSize=1 is correct; previous_cnt = group_cnt - __popc(vote >> thread_rank) correctly yields per-thread output offset.
corelib/dynamicemb/src/jit/evict_lrulfu.cu Adds run_insert_collect and dyn_emb_insert_collect_entry for LruLfu collect path, consistent with the pre-existing run_insert pattern (OutputScore=true hardcoded; null check in insert_body handles the no-score case).
corelib/dynamicemb/dynamicemb/scored_hashtable.py Adds collect_evicted parameter to LinearBucketTable.insert, routing to the new table_insert_collect_evicted C++ binding or raising RuntimeError under DEMB_DETERMINISM_MODE.
corelib/dynamicemb/dynamicemb/batched_dynamicemb_function.py Extends _prefetch_hbm_direct_path to collect evicted keys when state.evicted_item_mode == RETAIN_KEY, using the new collect_evicted=True insert path and _append_evicted. Logic is symmetric with _insert_key_values collection.

Sequence Diagram

sequenceDiagram
    participant U as User Code
    participant BDT as BatchedDynamicEmbeddingTablesV2
    participant S as DynamicEmbStorage / HybridStorage
    participant KIM as key_index_map (LinearBucketTable)
    participant CUDA as CUDA Kernel (insert_collect)

    Note over U,CUDA: Forward pass - retain evicted keys
    U->>BDT: forward(keys)
    BDT->>S: _insert_key_values(state, keys, table_ids, values)
    S->>KIM: "insert(keys, table_ids, score, collect_evicted=True)"
    KIM->>CUDA: table_insert_collect_evicted(...)
    CUDA-->>KIM: (indices, num_evicted, evicted_keys, evicted_table_ids)
    KIM-->>S: (indices, num_evicted, evicted_keys, evicted_table_ids)
    S->>S: _append_evicted(state, evicted_keys, evicted_table_ids, num_evicted)
    Note over S: evicted_key_chunks grows (one D2H sync per evicting insert)

    Note over U,CUDA: Checkpoint / incremental dump
    U->>BDT: incremental_dump(named_thresholds, pg)
    BDT->>S: storage.incremental_dump(table_id, threshold, pg)
    S-->>BDT: (keys_cat, values_cat, slot_index)
    BDT->>S: storage.pop_evicted_keys(table_id)
    S->>S: _pop_state_evicted_keys(state, table_id)
    S-->>BDT: evicted_keys tensor
    BDT->>BDT: _all_gather_evicted_keys(ev, pg) [if distributed]
    BDT-->>U: DeltaDumpResult(table_names, keys, values, evicted_keys, meta)

    Note over U,CUDA: Standalone evicted-key pop
    U->>BDT: pop_evicted_keys(table_names, pg)
    BDT->>S: storage.pop_evicted_keys(table_id)
    S-->>BDT: local evicted keys
    BDT->>BDT: _all_gather_evicted_keys(keys, pg) [if pg given]
    BDT-->>U: Dict[collection_path, Dict[table_name, keys]]
Loading

Reviews (10): Last reviewed commit: "refactor(dynamicemb): replace retain_evi..." | Re-trigger Greptile

@jiashuy

jiashuy commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator Author

/build

@jiashuy
jiashuy force-pushed the feat/dynamicemb-retain-evicted-keys branch from d2b3a3a to ef853ee Compare July 27, 2026 02:15
@jiashuy

jiashuy commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator Author

/build

@JacoCheung

JacoCheung commented Jul 27, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Pipeline #59720030 -- success

Job Status Log
pre_check ❌ failed view
train_build_x86 ✅ success view
train_build_arm64 ✅ success view
prepare-jet-b200-smoke ✅ success view
prepare-jet-b200-inference ✅ success view
prepare-jet-cw-dfw-e2e-benchmark ✅ success view
build_whl ✅ success view
dynamicemb_test_fwd_bwd_8gpus ✅ success view
dynamicemb_test_load_dump_8gpus ✅ success view
unit_test_1gpu_a100 ✅ success view
unit_test_1gpu_h100 ✅ success view
unit_test_4gpu ✅ success view
unit_test_tp_4gpu ❌ failed view
L20_unit_test_1gpu ✅ success view
inference_unit_test_1gpu ✅ success view
inference_test_1gpu ✅ success view

Result: 14/16 jobs passed

View full pipeline

@jiashuy

jiashuy commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator Author

/build

@JacoCheung

JacoCheung commented Jul 30, 2026 •

Copy link
Copy Markdown
Collaborator

❌ Pipeline #60278154 -- failed

Job Status Log
pre_check ❌ failed view
train_build_x86 ✅ success view
train_build_arm64 ✅ success view
prepare-jet-b200-smoke ✅ success view
prepare-jet-b200-inference ✅ success view
prepare-jet-cw-dfw-e2e-benchmark ✅ success view
build_whl ✅ success view
dynamicemb_test_fwd_bwd_8gpus ❌ failed view
dynamicemb_test_load_dump_8gpus ✅ success view
unit_test_1gpu_a100 ✅ success view
unit_test_1gpu_h100 ✅ success view
unit_test_4gpu ✅ success view
unit_test_tp_4gpu ❌ failed view
L20_unit_test_1gpu ✅ success view
inference_unit_test_1gpu ✅ success view
inference_test_1gpu ❌ failed view

Result: 12/16 jobs passed

View full pipeline

@jiashuy

jiashuy commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

/build

@JacoCheung

JacoCheung commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Pipeline #60957577 -- success

Job Status Log
pre_check ❌ failed view
train_build_x86 ✅ success view
train_build_arm64 ✅ success view
prepare-jet-b200-smoke ✅ success view
prepare-jet-b200-inference ✅ success view
prepare-jet-cw-dfw-e2e-benchmark ✅ success view
build_whl ✅ success view
dynamicemb_test_fwd_bwd_8gpus ✅ success view
dynamicemb_test_load_dump_8gpus ✅ success view
unit_test_1gpu_a100 ✅ success view
unit_test_1gpu_h100 ✅ success view
unit_test_4gpu ✅ success view
unit_test_tp_4gpu ❌ failed view
L20_unit_test_1gpu ✅ success view
inference_unit_test_1gpu ✅ success view
inference_test_1gpu ✅ success view

Result: 14/16 jobs passed

View full pipeline

@jiashuy
jiashuy force-pushed the feat/dynamicemb-retain-evicted-keys branch from 3d9af3f to d8bdfc2 Compare August 6, 2026 02:46
jiashuy and others added 10 commits August 7, 2026 13:56
… API

Add an opt-in retain_evicted_keys table option so the last-tier storage records the keys it evicts (instead of silently dropping them), plus a pop_evicted_keys API to read them back per table, unique and incrementally.

C++: insert_body gains a CollectEvicted template sink that compacts each Evict victim's (key, table_id); wired through a new AoT table_insert_collect_kernel and a dyn_emb_insert_collect_entry LruLfu cubin entry (reusing EvictParams, no ABI change), exposed as table_insert_collect_evicted. Covers all score policies. Only InsertResult::Evict is collected, not Busy.

Python: retain_evicted_keys config (in get_grouped_key so retain-differing tables don't share storage); the last-tier state accumulates evicted (key, table_id) chunks, de-duplicated only on pop; DynamicEmbStorage / HybridStorage pop_evicted_keys; module- and model-level pop_evicted_keys with optional pg all_gather (else per-rank local, disjoint). Design doc under docs/.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…retain gap

Non-caching training forward inserts through _prefetch_hbm_direct_path, which calls key_index_map.insert() directly (bypassing _insert_key_values), so its last-tier eviction was never retained. Add the collect_evicted branch there too. (Prefetched keys are ref-counter protected, so eviction only materializes across forward+backward steps.)

New self-contained suite under test/unit_tests/retain_evicted_keys/ (12 cases): table (whole-set oracle for insert(collect_evicted=True) on LruLfu cubin + AoT, table_id routing, no-eviction, determinism raise); storage (DynamicEmbStorage end-to-end collect->pop unique->gone->incremental, retain=False empty, dedup/table_id-filter/clear-isolation unit); module (HBM-direct training retains = the gap above, disabled omitted, table_names filter); distributed model (row-wise sharded: pg=None disjoint per rank / pg union). Wired into unit_test.sh (fwd_bwd group).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Also sync a few stale spots to the as-built code: retain buffers are tensor chunk lists (not ExtendableBuffer), pop returns host tensors, tests live under test/unit_tests/retain_evicted_keys/ (distributed test included), and the API lives in incremental_dump.py.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Refactor incremental_dump's return from (ret_tensors, ret_scores) to
Dict[collection_path, DeltaDumpResult], packing per-collection
column-aligned lists (table_names/keys/values/evicted_keys/meta) with a
slot_index that pins each key to its physical row for a future precise
replay_increment.

- slot_index encoding: single-tier normal = key_slot (== value row);
  NO_EVICTION = (key_slot << 32) | value_row; HybridStorage = bit63 tier
  | bits0-62 key_slot.
- HybridStorage + NO_EVICTION now raises (non-caching partial-HBM storage
  cannot host the NO_EVICTION auto-increment score policy).
- pop_evicted_keys returns a host tensor (CUDA-accelerated internally).
- incremental_dump accepts an optional pg; keys/values/evicted/slot_index
  are all_gathered within it (dist_type "continuous" unsupported -> raise).
- meta.world_size records the table's ROW_WISE shard fan-out (global
  dist.get_world_size(), which equals input_dist's pg.size()).
- Tests: DeltaDumpResult adaptations, HybridStorage tier slot_index test,
  skip NO_EVICTION+partial-HBM combo; docs: DeltaDumpResult design +
  DynamicEmb_APIs updates.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
test_hybrid_incremental_dump_slot_index_tier inserted a fixed 256 keys and
asserted both tiers contribute dumped keys. But the HBM tier's per-rank
capacity is global_capacity / world_size, so on a single GPU (world_size 1)
the HBM tier holds all 256 keys, nothing is evicted, and the host tier stays
empty -> the "host tier must contribute dumped keys" assert fails. The test
only passed at world_size >= 2.

Derive the insert count from the actual HBM capacity instead:
n = hbm_cap + min(hbm_cap, host_cap). This fills the HBM tier and overflows
enough to guarantee a spill into the host tier on any world_size. Verified
passing on both nproc=1 and nproc=2.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Run black 23.9.1 (pre-commit) over the dynamicemb files this branch adds or
modifies -- pure formatting, no logic changes. They were committed earlier
without running black (local dev had no pre-commit hook).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…function closures

Small PR#437-debt cleanups (these files landed via NVIDIA#437; touched here because
this branch builds directly on them):

- score.cuh: the LruLfu comment said tables are "created with
  need_incremental_dump=True", but that parameter no longer exists -- they are
  created with a compound (TIMESTAMP, LFU) score_strategy.
- lru_lfu_score_strategy_design.md: replace all 13 stale need_incremental_dump
  references (a removed parameter, incl. a wrong get_score_policy signature)
  with the actual "(TIMESTAMP, LFU) / existing incremental-dump LruLfu" terms.
- score_jit.py: _remap_score_function recompiles against fn.__globals__ only,
  silently dropping closure captures, so a factory/closure score_function later
  failed with an opaque numba NameError. Reject co_freevars up front with a
  clear ValueError. Verified on EOS: closure raises, plain fns unaffected,
  test_lru_lfu 19 passed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
_pop_state_evicted_keys' empty guard hardcoded torch.int64, but the non-empty
path returns torch.cat(chunks) whose dtype is key_index_map.key_type (== the
table's index_type, which can be int32/uint32). For int32-key tables the two
paths returned different dtypes, so a caller concatenating or comparing across
empty and non-empty pops would hit a RuntimeError. Return
state.key_index_map.key_type from the empty guard -- the same dtype the
non-empty path carries.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ist_type

incremental_dump's slot_index targets precise replay_increment, which
reconstructs each key's owning rank via (key or hash(key)) % world_size --
only defined for roundrobin / hash_roundrobin. A table sharded with
dist_type="continuous" uses a range-based key->rank mapping this path does not
implement and raises NotImplementedError. Document the limitation in the
incremental_dump API section.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…emMode enum

Replace the boolean DynamicEmbTableOptions.retain_evicted_keys with an
extensible enum EvictedItemMode { DISCARD (default), RETAIN_KEY }, leaving room
for future modes (e.g. RETAIN_VALUE) without another API change. Unreleased in
this branch, so no bool alias -- all usages updated: config (enum + field +
get_grouped_key), state field + branches (key_value_table,
batched_dynamicemb_{tables,function}), scored_hashtable message,
incremental_dump docstrings, __init__ export, the three retain tests, and the
API + design docs.

Also finalizes the empty-pop dtype test from the earlier dtype fix (d53eb76):
parametrized int64/uint64, empty-only -- a uint64 table's non-empty pop hits
torch's unimplemented UInt64 GPU indexing, tracked separately.

Verified on EOS: retain suite 8 + 5 + 1 passed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@jiashuy
jiashuy force-pushed the feat/dynamicemb-retain-evicted-keys branch from 6db63d4 to 95a2552 Compare August 7, 2026 08:26
@jiashuy

jiashuy commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

/build

@JacoCheung

JacoCheung commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

❌ Pipeline #61541059 -- failed

Job Status Log
pre_check ❌ failed view
train_build_x86 ✅ success view
train_build_arm64 ✅ success view
prepare-jet-b200-smoke ✅ success view
prepare-jet-b200-inference ✅ success view
prepare-jet-cw-dfw-e2e-benchmark ✅ success view
build_whl ✅ success view
dynamicemb_test_fwd_bwd_8gpus ✅ success view
dynamicemb_test_load_dump_8gpus ✅ success view
unit_test_1gpu_a100 ✅ success view
unit_test_1gpu_h100 ✅ success view
unit_test_4gpu ❌ failed view
unit_test_tp_4gpu ❌ failed view
L20_unit_test_1gpu ✅ success view
inference_unit_test_1gpu ✅ success view
inference_test_1gpu ✅ success view

Result: 13/16 jobs passed

View full pipeline

@jiashuy

jiashuy commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

This PR is ready @shijieliu

@shijieliu
shijieliu merged commit 9a3bf5d into NVIDIA:main Aug 10, 2026
1 check passed
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.

3 participants