Repository navigation
Feat/dynamicemb Implementation of LFU_DECAY by costimized JIT function - #437
Conversation
Greptile SummaryThis PR implements the
Confidence Score: 4/5The PR is nearly complete and correct, but the Reclaim branch in kernels.cuh leaves a stale LruLfu frequency word when a new key occupies a slot vacated by erase, corrupting LFU eviction ranking for those keys. The Evict path was fixed to clear all score words, but the Reclaim path (slots emptied by table_erase_kernel) was missed. The erase kernel zeroes only word 0; word 1 retains the erased key's accumulated frequency. Any LruLfu table that calls erase() and then re-inserts keys into those slots will silently assign phantom frequency to the new keys, undermining the LFU ordering guarantee. Files Needing Attention: corelib/dynamicemb/src/table_operation/kernels.cuh — the Reclaim branch in the insert() function body needs the same score-block zeroing loop added in the Evict branch. Important Files Changed
Reviews (15): Last reviewed commit: "fix(dynamicemb): make score_function_key..." | Re-trigger Greptile |
90113a2 to
a1bcf2d
Compare
|
/build |
|
❌ Pipeline #57231345 -- failed
Result: 10/17 jobs passed |
a1bcf2d to
2da155f
Compare
|
/build |
|
❌ Pipeline #58387906 -- failed
Result: 11/17 jobs passed |
2da155f to
9ecc190
Compare
|
/build |
|
❌ Pipeline #58407279 -- failed
Result: 13/17 jobs passed |
|
/build |
|
❌ Pipeline #58712240 -- failed
Result: 14/17 jobs passed |
3c7e3c0 to
a2e67b9
Compare
Express LRU+LFU eviction through the compound score strategy (TIMESTAMP, LFU) (either tuple order): word0 = last-access timestamp, word1 = frequency. By default eviction ranks by frequency with an older-timestamp tiebreak; it can be fully customized via a user-supplied score_function. - score_function(scores, cur_timestamp) -> float64 is numba-compiled to LTO-IR and nvJitLink-linked into a prebuilt custom eviction cubin at registration time; the driver launches it for all 2-word eviction. - The default path uses a prebuilt Lex (frequency -> older-timestamp) comparator cubin -- no numba required. - Users index `scores` in logical (tuple) order; subscripts must be integer constants and are statically remapped to physical device words via score_dump_permutation, so (LFU, TIMESTAMP) works transparently. - Custom cubins are cached per (device, function, score order). Two prebuilt fatbins (Lex + custom) are compiled per-arch at build time and shipped as package_data. Tests: 18 table-level tests including whole-set eviction oracles for the default timestamp tiebreak, custom decay, logical!=physical remap, and an end-to-end BatchedDynamicEmbeddingTablesV2 path. Co-Authored-By: Claude Opus 4.8 <[email protected]>
A full bucket can be evicted by the plain insert path (table_insert), not just insert_and_evict. That path used DefaultEvictor -> the single-score reduce(), which cannot read the 2-word AoS LruLfu layout, so a plain insert that overflowed a bucket would pick a garbage victim (and ignore any custom score_function). Only insert_and_evict was wired to the eviction cubin. Route the num_scores==2 plain-insert eviction through the same cubin: - Factor table_insert_kernel's body into insert_body<Table,KernelTraits,Evictor> so both the AoT kernel (DefaultEvictor) and the cubin (RankedEvictor<Comparator>) share it. - Add a third cubin entry dyn_emb_insert_entry (reuses EvictParams; collects no evicted output) + demb_get_insert_fn(); resolved/cached like the evict entries. - launch_table_insert_kernel routes PolicyType==LruLfu to the cubin (default Lex when score_fn_key==0, else the custom evictor); thread score_fn_key through table_insert and ScoredHashTable.insert(). The plain insert still drops the evicted key (unchanged semantics) but now selects the correct victim (freq->ts tiebreak by default, or the custom decay). Test: table.insert() overflowing a full bucket with _evict_high_freq_first must evict the hot keys (DefaultEvictor would have kept them). Co-Authored-By: Claude Opus 4.8 <[email protected]>
- compile_evict_fatbins: add --expt-relaxed-constexpr / --expt-extended-lambda so the fatbin TU compiles kernels.cuh (<cub/cub.cuh>, cooperative_groups) with the same flags as the main extension build, avoiding cross-CUDA-version skew. - jit_link.cpp load_from_image: cuModuleUnload the just-loaded module if any cuModuleGetFunction fails, instead of leaking it. - jit_link.cpp link_custom: destroy the nvJitLinkHandle on every exit path via an RAII guard (jl_check / load_from_image can throw), instead of leaking it when linking fails. Co-Authored-By: Claude Opus 4.8 <[email protected]>
cuda.compile was given only the argument types, so numba inferred the return type from the body. A score_function returning an integer expression (e.g. `return -scores[1]` without a float() cast) would compile to an integer-register return, which the C++ `extern "C" __device__ double user_score_fn(...)` caller reads as junk double bits -- a silent miscompile that degrades eviction to an arbitrary order. Pin the signature to float64(CPointer(uint64), uint64) so numba casts the return value to double instead. Co-Authored-By: Claude Opus 4.8 <[email protected]>
- evict_lrulfu.cu header: three entry points (evict ovf/noovf + plain insert), reuses insert_body too -- not "two entry points, insert_and_evict_body only". - score_jit.py docstring: register_score_function takes (cc_major, cc_minor). - lru_lfu_score_strategy_design.md: replace the stale "no code written yet" status with an as-built banner (compound tuple instead of an LRU_LFU enum, no gamma, three cubin entries, plain insert also routes through the cubin); keep the body as the original design rationale, code is the source of truth. Co-Authored-By: Claude Opus 4.8 <[email protected]>
- DynamicEmb_APIs.md: add a "Customized eviction via score_function" section
under DynamicEmbScoreStrategy (signature, logical-order indexing, numba-cuda
requirement, worked example) and a score_function field entry under
DynamicEmbTableOptions. Make the constraint explicit: score_function is
supported ONLY for the two-word {TIMESTAMP, LFU} compound (scores length 2);
any other score_strategy with a score_function raises ValueError.
- example/example.py: add an example lru_lfu_decay_score (time-decayed LFU) and a
--score_strategy {step,timestamp,lru_lfu} flag that wires the compound
(TIMESTAMP, LFU) tuple + score_function into DynamicEmbTableOptions.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Scrub the remaining proposal-era divergences so the design doc describes the shipped implementation (code stays the source of truth), keeping the rationale: - Drop `lfu_decay_gamma` and the `(scores, cur_timestamp, gamma)` signature everywhere; the score_function is `(scores, cur_timestamp) -> float64` with any decay constant written in the body. - No `LRU_LFU` enum: the strategy is the compound `(TIMESTAMP, LFU)` tuple; update the goal, API, example, and component table accordingly. - score_function indexes `scores` in logical (tuple) order with a static logical→physical remap (not "zero remapping"). - Three cubin entries (`dyn_emb_evict_entry_ovf`/`_noovf` + `dyn_emb_insert_entry`) and plain insert also routes through the cubin (two call sites); fix the ABI struct (no gamma field), §11 entry/launch text, and the build-check. - cuda.compile pins the float64 return type; module cache keyed by (device, key). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…e/order - README.md: add a "Customized Eviction Score" section under Usage Notes (compound (TIMESTAMP, LFU) + score_function example, numba-cuda requirement, pointer to the API doc). - DynamicEmb_APIs.md: add a "Compound (multi-score) strategies and score order" section that spells out, in user-facing terms, that a compound strategy keeps more than one score per key and that the tuple order controls two things that always agree — the score column order dumped to file, and how score_function indexes scores — while eviction is identical either way. Reword the score_function / score_strategy text to drop implementation details. - lru_lfu_score_strategy_design.md: fold in the remaining LRU_LFU -> compound-tuple precision fixes (LruLfu spec/strategy/table naming, device-keyed cache) that the prior design-doc rewrite commit missed. Co-Authored-By: Claude Opus 4.8 <[email protected]>
… guards) Two cheap defensive guards on the JIT eviction path: - UserFnComparator::rank clamps a NaN user score to -inf (evict-first). A NaN compares false against every candidate, so it could never be picked as the eviction minimum, and an all-NaN bucket would find no victim and silently drop the incoming key. Clamping keeps eviction deterministic and inserts progressing. Document the finite-return contract (comparator header + API doc). - reduce()/reduce_ranked() assert num_scores_ == 1 / == 2 respectively, so a misrouted call fails loud instead of silently misreading the layout (nvcc is not built with -DNDEBUG, so the device assert is live). Guards a future regression; after the plain-insert routing both paths already send num_scores==2 to the cubin. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…lti-GPU) score_function_key ignored the device compute capability, so on a single process driving GPUs of different arch the custom score_function registered only the first device's numba LTO-IR (the Python _registered_keys dedup short-circuited the others). A later different-arch device then linked that LTO-IR under the wrong -arch and cuModuleLoadData failed on its first custom-eviction insert. Include cc in the key so each arch gets a distinct key -> its own numba compile and C++ registration (cc is already stored per key, so link_custom picks the right -arch). No C++ change needed. Same-arch devices still share one key/compile with the module cached per device, so homogeneous setups are unaffected. Co-Authored-By: Claude Opus 4.8 <[email protected]>
9579353 to
f2b242d
Compare
|
/build |
|
❌ Pipeline #60279091 -- failed
Result: 10/14 jobs passed |
…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]>
…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]>
* feat(dynamicemb): retain evicted keys at last tier + pop_evicted_keys 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]> * test(dynamicemb): retain_evicted_keys suite + fix HBM-direct forward 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]> * docs(dynamicemb): translate retain_evicted_keys_design.md to English 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]> * feat(dynamicemb): return DeltaDumpResult map from incremental_dump 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]> * fix(dynamicemb): make hybrid tier slot_index test world_size-agnostic 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]> * style(dynamicemb): apply black formatting via pre-commit 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]> * docs(dynamicemb): fix stale need_incremental_dump refs + guard score_function closures Small PR#437-debt cleanups (these files landed via #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]> * fix(dynamicemb): keep pop_evicted_keys empty/non-empty dtype consistent _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]> * docs(dynamicemb): note incremental_dump does not support continuous dist_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]> * refactor(dynamicemb): replace retain_evicted_keys bool with EvictedItemMode 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]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Description
Checklist